babylon.no-module.max.js 4.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855
  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. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9291. if (("download" in document.createElement("a"))) {
  9292. if (!fileName) {
  9293. var date = new Date();
  9294. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9295. fileName = "screenshot_" + stringDate + ".png";
  9296. }
  9297. Tools.Download(blob, fileName);
  9298. }
  9299. else {
  9300. var url = URL.createObjectURL(blob);
  9301. var newWindow = window.open("");
  9302. if (!newWindow)
  9303. return;
  9304. var img = newWindow.document.createElement("img");
  9305. img.onload = function () {
  9306. // no longer need to read the blob so it's revoked
  9307. URL.revokeObjectURL(url);
  9308. };
  9309. img.src = url;
  9310. newWindow.document.body.appendChild(img);
  9311. }
  9312. });
  9313. }
  9314. };
  9315. /**
  9316. * Downloads a blob in the browser
  9317. * @param blob defines the blob to download
  9318. * @param fileName defines the name of the downloaded file
  9319. */
  9320. Tools.Download = function (blob, fileName) {
  9321. var url = window.URL.createObjectURL(blob);
  9322. var a = document.createElement("a");
  9323. document.body.appendChild(a);
  9324. a.style.display = "none";
  9325. a.href = url;
  9326. a.download = fileName;
  9327. a.addEventListener("click", function () {
  9328. if (a.parentElement) {
  9329. a.parentElement.removeChild(a);
  9330. }
  9331. });
  9332. a.click();
  9333. window.URL.revokeObjectURL(url);
  9334. };
  9335. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9336. if (mimeType === void 0) { mimeType = "image/png"; }
  9337. var width;
  9338. var height;
  9339. // If a precision value is specified
  9340. if (size.precision) {
  9341. width = Math.round(engine.getRenderWidth() * size.precision);
  9342. height = Math.round(width / engine.getAspectRatio(camera));
  9343. }
  9344. else if (size.width && size.height) {
  9345. width = size.width;
  9346. height = size.height;
  9347. }
  9348. //If passing only width, computing height to keep display canvas ratio.
  9349. else if (size.width && !size.height) {
  9350. width = size.width;
  9351. height = Math.round(width / engine.getAspectRatio(camera));
  9352. }
  9353. //If passing only height, computing width to keep display canvas ratio.
  9354. else if (size.height && !size.width) {
  9355. height = size.height;
  9356. width = Math.round(height * engine.getAspectRatio(camera));
  9357. }
  9358. //Assuming here that "size" parameter is a number
  9359. else if (!isNaN(size)) {
  9360. height = size;
  9361. width = size;
  9362. }
  9363. else {
  9364. Tools.Error("Invalid 'size' parameter !");
  9365. return;
  9366. }
  9367. if (!screenshotCanvas) {
  9368. screenshotCanvas = document.createElement('canvas');
  9369. }
  9370. screenshotCanvas.width = width;
  9371. screenshotCanvas.height = height;
  9372. var renderContext = screenshotCanvas.getContext("2d");
  9373. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9374. var newWidth = width;
  9375. var newHeight = newWidth / ratio;
  9376. if (newHeight > height) {
  9377. newHeight = height;
  9378. newWidth = newHeight * ratio;
  9379. }
  9380. var offsetX = Math.max(0, width - newWidth) / 2;
  9381. var offsetY = Math.max(0, height - newHeight) / 2;
  9382. var renderingCanvas = engine.getRenderingCanvas();
  9383. if (renderContext && renderingCanvas) {
  9384. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9385. }
  9386. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9387. };
  9388. /**
  9389. * Generates an image screenshot from the specified camera.
  9390. *
  9391. * @param engine The engine to use for rendering
  9392. * @param camera The camera to use for rendering
  9393. * @param size This parameter can be set to a single number or to an object with the
  9394. * following (optional) properties: precision, width, height. If a single number is passed,
  9395. * it will be used for both width and height. If an object is passed, the screenshot size
  9396. * will be derived from the parameters. The precision property is a multiplier allowing
  9397. * rendering at a higher or lower resolution.
  9398. * @param successCallback The callback receives a single parameter which contains the
  9399. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9400. * src parameter of an <img> to display it.
  9401. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9402. * Check your browser for supported MIME types.
  9403. * @param samples Texture samples (default: 1)
  9404. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9405. * @param fileName A name for for the downloaded file.
  9406. * @constructor
  9407. */
  9408. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9409. if (mimeType === void 0) { mimeType = "image/png"; }
  9410. if (samples === void 0) { samples = 1; }
  9411. if (antialiasing === void 0) { antialiasing = false; }
  9412. var width;
  9413. var height;
  9414. //If a precision value is specified
  9415. if (size.precision) {
  9416. width = Math.round(engine.getRenderWidth() * size.precision);
  9417. height = Math.round(width / engine.getAspectRatio(camera));
  9418. size = { width: width, height: height };
  9419. }
  9420. else if (size.width && size.height) {
  9421. width = size.width;
  9422. height = size.height;
  9423. }
  9424. //If passing only width, computing height to keep display canvas ratio.
  9425. else if (size.width && !size.height) {
  9426. width = size.width;
  9427. height = Math.round(width / engine.getAspectRatio(camera));
  9428. size = { width: width, height: height };
  9429. }
  9430. //If passing only height, computing width to keep display canvas ratio.
  9431. else if (size.height && !size.width) {
  9432. height = size.height;
  9433. width = Math.round(height * engine.getAspectRatio(camera));
  9434. size = { width: width, height: height };
  9435. }
  9436. //Assuming here that "size" parameter is a number
  9437. else if (!isNaN(size)) {
  9438. height = size;
  9439. width = size;
  9440. }
  9441. else {
  9442. Tools.Error("Invalid 'size' parameter !");
  9443. return;
  9444. }
  9445. var scene = camera.getScene();
  9446. var previousCamera = null;
  9447. if (scene.activeCamera !== camera) {
  9448. previousCamera = scene.activeCamera;
  9449. scene.activeCamera = camera;
  9450. }
  9451. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9452. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9453. texture.renderList = null;
  9454. texture.samples = samples;
  9455. if (antialiasing) {
  9456. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9457. }
  9458. texture.onAfterRenderObservable.add(function () {
  9459. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9460. });
  9461. scene.incrementRenderId();
  9462. scene.resetCachedMaterial();
  9463. texture.render(true);
  9464. texture.dispose();
  9465. if (previousCamera) {
  9466. scene.activeCamera = previousCamera;
  9467. }
  9468. camera.getProjectionMatrix(true); // Force cache refresh;
  9469. };
  9470. // XHR response validator for local file scenario
  9471. Tools.ValidateXHRData = function (xhr, dataType) {
  9472. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9473. if (dataType === void 0) { dataType = 7; }
  9474. try {
  9475. if (dataType & 1) {
  9476. if (xhr.responseText && xhr.responseText.length > 0) {
  9477. return true;
  9478. }
  9479. else if (dataType === 1) {
  9480. return false;
  9481. }
  9482. }
  9483. if (dataType & 2) {
  9484. // Check header width and height since there is no "TGA" magic number
  9485. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9486. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9487. return true;
  9488. }
  9489. else if (dataType === 2) {
  9490. return false;
  9491. }
  9492. }
  9493. if (dataType & 4) {
  9494. // Check for the "DDS" magic number
  9495. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9496. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9497. return true;
  9498. }
  9499. else {
  9500. return false;
  9501. }
  9502. }
  9503. }
  9504. catch (e) {
  9505. // Global protection
  9506. }
  9507. return false;
  9508. };
  9509. /**
  9510. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9511. * Be aware Math.random() could cause collisions, but:
  9512. * "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"
  9513. */
  9514. Tools.RandomId = function () {
  9515. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9516. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9517. return v.toString(16);
  9518. });
  9519. };
  9520. /**
  9521. * Test if the given uri is a base64 string.
  9522. * @param uri The uri to test
  9523. * @return True if the uri is a base64 string or false otherwise.
  9524. */
  9525. Tools.IsBase64 = function (uri) {
  9526. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9527. };
  9528. /**
  9529. * Decode the given base64 uri.
  9530. * @param uri The uri to decode
  9531. * @return The decoded base64 data.
  9532. */
  9533. Tools.DecodeBase64 = function (uri) {
  9534. var decodedString = atob(uri.split(",")[1]);
  9535. var bufferLength = decodedString.length;
  9536. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9537. for (var i = 0; i < bufferLength; i++) {
  9538. bufferView[i] = decodedString.charCodeAt(i);
  9539. }
  9540. return bufferView.buffer;
  9541. };
  9542. Object.defineProperty(Tools, "NoneLogLevel", {
  9543. get: function () {
  9544. return Tools._NoneLogLevel;
  9545. },
  9546. enumerable: true,
  9547. configurable: true
  9548. });
  9549. Object.defineProperty(Tools, "MessageLogLevel", {
  9550. get: function () {
  9551. return Tools._MessageLogLevel;
  9552. },
  9553. enumerable: true,
  9554. configurable: true
  9555. });
  9556. Object.defineProperty(Tools, "WarningLogLevel", {
  9557. get: function () {
  9558. return Tools._WarningLogLevel;
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(Tools, "ErrorLogLevel", {
  9564. get: function () {
  9565. return Tools._ErrorLogLevel;
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(Tools, "AllLogLevel", {
  9571. get: function () {
  9572. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Tools._AddLogEntry = function (entry) {
  9578. Tools._LogCache = entry + Tools._LogCache;
  9579. if (Tools.OnNewCacheEntry) {
  9580. Tools.OnNewCacheEntry(entry);
  9581. }
  9582. };
  9583. Tools._FormatMessage = function (message) {
  9584. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9585. var date = new Date();
  9586. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9587. };
  9588. Tools._LogDisabled = function (message) {
  9589. // nothing to do
  9590. };
  9591. Tools._LogEnabled = function (message) {
  9592. var formattedMessage = Tools._FormatMessage(message);
  9593. console.log("BJS - " + formattedMessage);
  9594. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9595. Tools._AddLogEntry(entry);
  9596. };
  9597. Tools._WarnDisabled = function (message) {
  9598. // nothing to do
  9599. };
  9600. Tools._WarnEnabled = function (message) {
  9601. var formattedMessage = Tools._FormatMessage(message);
  9602. console.warn("BJS - " + formattedMessage);
  9603. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9604. Tools._AddLogEntry(entry);
  9605. };
  9606. Tools._ErrorDisabled = function (message) {
  9607. // nothing to do
  9608. };
  9609. Tools._ErrorEnabled = function (message) {
  9610. Tools.errorsCount++;
  9611. var formattedMessage = Tools._FormatMessage(message);
  9612. console.error("BJS - " + formattedMessage);
  9613. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9614. Tools._AddLogEntry(entry);
  9615. };
  9616. Object.defineProperty(Tools, "LogCache", {
  9617. get: function () {
  9618. return Tools._LogCache;
  9619. },
  9620. enumerable: true,
  9621. configurable: true
  9622. });
  9623. Tools.ClearLogCache = function () {
  9624. Tools._LogCache = "";
  9625. Tools.errorsCount = 0;
  9626. };
  9627. Object.defineProperty(Tools, "LogLevels", {
  9628. set: function (level) {
  9629. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9630. Tools.Log = Tools._LogEnabled;
  9631. }
  9632. else {
  9633. Tools.Log = Tools._LogDisabled;
  9634. }
  9635. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9636. Tools.Warn = Tools._WarnEnabled;
  9637. }
  9638. else {
  9639. Tools.Warn = Tools._WarnDisabled;
  9640. }
  9641. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9642. Tools.Error = Tools._ErrorEnabled;
  9643. }
  9644. else {
  9645. Tools.Error = Tools._ErrorDisabled;
  9646. }
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Tools.IsWindowObjectExist = function () {
  9652. return (typeof window) !== "undefined";
  9653. };
  9654. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9655. get: function () {
  9656. return Tools._PerformanceNoneLogLevel;
  9657. },
  9658. enumerable: true,
  9659. configurable: true
  9660. });
  9661. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9662. get: function () {
  9663. return Tools._PerformanceUserMarkLogLevel;
  9664. },
  9665. enumerable: true,
  9666. configurable: true
  9667. });
  9668. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9669. get: function () {
  9670. return Tools._PerformanceConsoleLogLevel;
  9671. },
  9672. enumerable: true,
  9673. configurable: true
  9674. });
  9675. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9676. set: function (level) {
  9677. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9678. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9679. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9680. return;
  9681. }
  9682. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9683. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9684. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9685. return;
  9686. }
  9687. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9688. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9689. },
  9690. enumerable: true,
  9691. configurable: true
  9692. });
  9693. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9694. };
  9695. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9696. };
  9697. Tools._StartUserMark = function (counterName, condition) {
  9698. if (condition === void 0) { condition = true; }
  9699. if (!Tools._performance) {
  9700. if (!Tools.IsWindowObjectExist()) {
  9701. return;
  9702. }
  9703. Tools._performance = window.performance;
  9704. }
  9705. if (!condition || !Tools._performance.mark) {
  9706. return;
  9707. }
  9708. Tools._performance.mark(counterName + "-Begin");
  9709. };
  9710. Tools._EndUserMark = function (counterName, condition) {
  9711. if (condition === void 0) { condition = true; }
  9712. if (!condition || !Tools._performance.mark) {
  9713. return;
  9714. }
  9715. Tools._performance.mark(counterName + "-End");
  9716. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9717. };
  9718. Tools._StartPerformanceConsole = function (counterName, condition) {
  9719. if (condition === void 0) { condition = true; }
  9720. if (!condition) {
  9721. return;
  9722. }
  9723. Tools._StartUserMark(counterName, condition);
  9724. if (console.time) {
  9725. console.time(counterName);
  9726. }
  9727. };
  9728. Tools._EndPerformanceConsole = function (counterName, condition) {
  9729. if (condition === void 0) { condition = true; }
  9730. if (!condition) {
  9731. return;
  9732. }
  9733. Tools._EndUserMark(counterName, condition);
  9734. if (console.time) {
  9735. console.timeEnd(counterName);
  9736. }
  9737. };
  9738. Object.defineProperty(Tools, "Now", {
  9739. get: function () {
  9740. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9741. return window.performance.now();
  9742. }
  9743. return Date.now();
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. /**
  9749. * This method will return the name of the class used to create the instance of the given object.
  9750. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9751. * @param object the object to get the class name from
  9752. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9753. */
  9754. Tools.GetClassName = function (object, isType) {
  9755. if (isType === void 0) { isType = false; }
  9756. var name = null;
  9757. if (!isType && object.getClassName) {
  9758. name = object.getClassName();
  9759. }
  9760. else {
  9761. if (object instanceof Object) {
  9762. var classObj = isType ? object : Object.getPrototypeOf(object);
  9763. name = classObj.constructor["__bjsclassName__"];
  9764. }
  9765. if (!name) {
  9766. name = typeof object;
  9767. }
  9768. }
  9769. return name;
  9770. };
  9771. Tools.First = function (array, predicate) {
  9772. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9773. var el = array_1[_i];
  9774. if (predicate(el)) {
  9775. return el;
  9776. }
  9777. }
  9778. return null;
  9779. };
  9780. /**
  9781. * This method will return the name of the full name of the class, including its owning module (if any).
  9782. * 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).
  9783. * @param object the object to get the class name from
  9784. * @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.
  9785. */
  9786. Tools.getFullClassName = function (object, isType) {
  9787. if (isType === void 0) { isType = false; }
  9788. var className = null;
  9789. var moduleName = null;
  9790. if (!isType && object.getClassName) {
  9791. className = object.getClassName();
  9792. }
  9793. else {
  9794. if (object instanceof Object) {
  9795. var classObj = isType ? object : Object.getPrototypeOf(object);
  9796. className = classObj.constructor["__bjsclassName__"];
  9797. moduleName = classObj.constructor["__bjsmoduleName__"];
  9798. }
  9799. if (!className) {
  9800. className = typeof object;
  9801. }
  9802. }
  9803. if (!className) {
  9804. return null;
  9805. }
  9806. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9807. };
  9808. /**
  9809. * 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.
  9810. * @param array
  9811. */
  9812. Tools.arrayOrStringFeeder = function (array) {
  9813. return function (index) {
  9814. if (index >= array.length) {
  9815. return null;
  9816. }
  9817. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9818. if (val && val.getHashCode) {
  9819. val = val.getHashCode();
  9820. }
  9821. if (typeof val === "string") {
  9822. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9823. }
  9824. return val;
  9825. };
  9826. };
  9827. /**
  9828. * Compute the hashCode of a stream of number
  9829. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9830. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9831. * @return the hash code computed
  9832. */
  9833. Tools.hashCodeFromStream = function (feeder) {
  9834. // Based from here: http://stackoverflow.com/a/7616484/802124
  9835. var hash = 0;
  9836. var index = 0;
  9837. var chr = feeder(index++);
  9838. while (chr != null) {
  9839. hash = ((hash << 5) - hash) + chr;
  9840. hash |= 0; // Convert to 32bit integer
  9841. chr = feeder(index++);
  9842. }
  9843. return hash;
  9844. };
  9845. /**
  9846. * Returns a promise that resolves after the given amount of time.
  9847. * @param delay Number of milliseconds to delay
  9848. * @returns Promise that resolves after the given amount of time
  9849. */
  9850. Tools.DelayAsync = function (delay) {
  9851. return new Promise(function (resolve) {
  9852. setTimeout(function () {
  9853. resolve();
  9854. }, delay);
  9855. });
  9856. };
  9857. Tools.BaseUrl = "";
  9858. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9859. /**
  9860. * Default behaviour for cors in the application.
  9861. * It can be a string if the expected behavior is identical in the entire app.
  9862. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9863. */
  9864. Tools.CorsBehavior = "anonymous";
  9865. Tools.UseFallbackTexture = true;
  9866. /**
  9867. * Use this object to register external classes like custom textures or material
  9868. * to allow the laoders to instantiate them
  9869. */
  9870. Tools.RegisteredExternalClasses = {};
  9871. // Used in case of a texture loading problem
  9872. 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";
  9873. Tools._tmpFloatArray = new Float32Array(1);
  9874. Tools.PreprocessUrl = function (url) {
  9875. return url;
  9876. };
  9877. // Logs
  9878. Tools._NoneLogLevel = 0;
  9879. Tools._MessageLogLevel = 1;
  9880. Tools._WarningLogLevel = 2;
  9881. Tools._ErrorLogLevel = 4;
  9882. Tools._LogCache = "";
  9883. Tools.errorsCount = 0;
  9884. Tools.Log = Tools._LogEnabled;
  9885. Tools.Warn = Tools._WarnEnabled;
  9886. Tools.Error = Tools._ErrorEnabled;
  9887. // Performances
  9888. Tools._PerformanceNoneLogLevel = 0;
  9889. Tools._PerformanceUserMarkLogLevel = 1;
  9890. Tools._PerformanceConsoleLogLevel = 2;
  9891. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9892. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9893. return Tools;
  9894. }());
  9895. BABYLON.Tools = Tools;
  9896. /**
  9897. * This class is used to track a performance counter which is number based.
  9898. * The user has access to many properties which give statistics of different nature
  9899. *
  9900. * The implementer can track two kinds of Performance Counter: time and count
  9901. * 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.
  9902. * 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.
  9903. */
  9904. var PerfCounter = /** @class */ (function () {
  9905. function PerfCounter() {
  9906. this._startMonitoringTime = 0;
  9907. this._min = 0;
  9908. this._max = 0;
  9909. this._average = 0;
  9910. this._lastSecAverage = 0;
  9911. this._current = 0;
  9912. this._totalValueCount = 0;
  9913. this._totalAccumulated = 0;
  9914. this._lastSecAccumulated = 0;
  9915. this._lastSecTime = 0;
  9916. this._lastSecValueCount = 0;
  9917. }
  9918. Object.defineProperty(PerfCounter.prototype, "min", {
  9919. /**
  9920. * Returns the smallest value ever
  9921. */
  9922. get: function () {
  9923. return this._min;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(PerfCounter.prototype, "max", {
  9929. /**
  9930. * Returns the biggest value ever
  9931. */
  9932. get: function () {
  9933. return this._max;
  9934. },
  9935. enumerable: true,
  9936. configurable: true
  9937. });
  9938. Object.defineProperty(PerfCounter.prototype, "average", {
  9939. /**
  9940. * Returns the average value since the performance counter is running
  9941. */
  9942. get: function () {
  9943. return this._average;
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9949. /**
  9950. * Returns the average value of the last second the counter was monitored
  9951. */
  9952. get: function () {
  9953. return this._lastSecAverage;
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Object.defineProperty(PerfCounter.prototype, "current", {
  9959. /**
  9960. * Returns the current value
  9961. */
  9962. get: function () {
  9963. return this._current;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(PerfCounter.prototype, "total", {
  9969. get: function () {
  9970. return this._totalAccumulated;
  9971. },
  9972. enumerable: true,
  9973. configurable: true
  9974. });
  9975. Object.defineProperty(PerfCounter.prototype, "count", {
  9976. get: function () {
  9977. return this._totalValueCount;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. /**
  9983. * Call this method to start monitoring a new frame.
  9984. * 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.
  9985. */
  9986. PerfCounter.prototype.fetchNewFrame = function () {
  9987. this._totalValueCount++;
  9988. this._current = 0;
  9989. this._lastSecValueCount++;
  9990. };
  9991. /**
  9992. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9993. * @param newCount the count value to add to the monitored count
  9994. * @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.
  9995. */
  9996. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9997. if (!PerfCounter.Enabled) {
  9998. return;
  9999. }
  10000. this._current += newCount;
  10001. if (fetchResult) {
  10002. this._fetchResult();
  10003. }
  10004. };
  10005. /**
  10006. * Start monitoring this performance counter
  10007. */
  10008. PerfCounter.prototype.beginMonitoring = function () {
  10009. if (!PerfCounter.Enabled) {
  10010. return;
  10011. }
  10012. this._startMonitoringTime = Tools.Now;
  10013. };
  10014. /**
  10015. * Compute the time lapsed since the previous beginMonitoring() call.
  10016. * @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
  10017. */
  10018. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10019. if (newFrame === void 0) { newFrame = true; }
  10020. if (!PerfCounter.Enabled) {
  10021. return;
  10022. }
  10023. if (newFrame) {
  10024. this.fetchNewFrame();
  10025. }
  10026. var currentTime = Tools.Now;
  10027. this._current = currentTime - this._startMonitoringTime;
  10028. if (newFrame) {
  10029. this._fetchResult();
  10030. }
  10031. };
  10032. PerfCounter.prototype._fetchResult = function () {
  10033. this._totalAccumulated += this._current;
  10034. this._lastSecAccumulated += this._current;
  10035. // Min/Max update
  10036. this._min = Math.min(this._min, this._current);
  10037. this._max = Math.max(this._max, this._current);
  10038. this._average = this._totalAccumulated / this._totalValueCount;
  10039. // Reset last sec?
  10040. var now = Tools.Now;
  10041. if ((now - this._lastSecTime) > 1000) {
  10042. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10043. this._lastSecTime = now;
  10044. this._lastSecAccumulated = 0;
  10045. this._lastSecValueCount = 0;
  10046. }
  10047. };
  10048. PerfCounter.Enabled = true;
  10049. return PerfCounter;
  10050. }());
  10051. BABYLON.PerfCounter = PerfCounter;
  10052. /**
  10053. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10054. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10055. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10056. * @param name The name of the class, case should be preserved
  10057. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10058. */
  10059. function className(name, module) {
  10060. return function (target) {
  10061. target["__bjsclassName__"] = name;
  10062. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10063. };
  10064. }
  10065. BABYLON.className = className;
  10066. /**
  10067. * An implementation of a loop for asynchronous functions.
  10068. */
  10069. var AsyncLoop = /** @class */ (function () {
  10070. /**
  10071. * Constroctor.
  10072. * @param iterations the number of iterations.
  10073. * @param _fn the function to run each iteration
  10074. * @param _successCallback the callback that will be called upon succesful execution
  10075. * @param offset starting offset.
  10076. */
  10077. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10078. if (offset === void 0) { offset = 0; }
  10079. this.iterations = iterations;
  10080. this._fn = _fn;
  10081. this._successCallback = _successCallback;
  10082. this.index = offset - 1;
  10083. this._done = false;
  10084. }
  10085. /**
  10086. * Execute the next iteration. Must be called after the last iteration was finished.
  10087. */
  10088. AsyncLoop.prototype.executeNext = function () {
  10089. if (!this._done) {
  10090. if (this.index + 1 < this.iterations) {
  10091. ++this.index;
  10092. this._fn(this);
  10093. }
  10094. else {
  10095. this.breakLoop();
  10096. }
  10097. }
  10098. };
  10099. /**
  10100. * Break the loop and run the success callback.
  10101. */
  10102. AsyncLoop.prototype.breakLoop = function () {
  10103. this._done = true;
  10104. this._successCallback();
  10105. };
  10106. /**
  10107. * Helper function
  10108. */
  10109. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10110. if (offset === void 0) { offset = 0; }
  10111. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10112. loop.executeNext();
  10113. return loop;
  10114. };
  10115. /**
  10116. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10117. * @param iterations total number of iterations
  10118. * @param syncedIterations number of synchronous iterations in each async iteration.
  10119. * @param fn the function to call each iteration.
  10120. * @param callback a success call back that will be called when iterating stops.
  10121. * @param breakFunction a break condition (optional)
  10122. * @param timeout timeout settings for the setTimeout function. default - 0.
  10123. * @constructor
  10124. */
  10125. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10126. if (timeout === void 0) { timeout = 0; }
  10127. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10128. if (breakFunction && breakFunction())
  10129. loop.breakLoop();
  10130. else {
  10131. setTimeout(function () {
  10132. for (var i = 0; i < syncedIterations; ++i) {
  10133. var iteration = (loop.index * syncedIterations) + i;
  10134. if (iteration >= iterations)
  10135. break;
  10136. fn(iteration);
  10137. if (breakFunction && breakFunction()) {
  10138. loop.breakLoop();
  10139. break;
  10140. }
  10141. }
  10142. loop.executeNext();
  10143. }, timeout);
  10144. }
  10145. }, callback);
  10146. };
  10147. return AsyncLoop;
  10148. }());
  10149. BABYLON.AsyncLoop = AsyncLoop;
  10150. })(BABYLON || (BABYLON = {}));
  10151. //# sourceMappingURL=babylon.tools.js.map
  10152. var BABYLON;
  10153. (function (BABYLON) {
  10154. var PromiseStates;
  10155. (function (PromiseStates) {
  10156. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10157. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10158. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10159. })(PromiseStates || (PromiseStates = {}));
  10160. var FulFillmentAgregator = /** @class */ (function () {
  10161. function FulFillmentAgregator() {
  10162. this.count = 0;
  10163. this.target = 0;
  10164. this.results = [];
  10165. }
  10166. return FulFillmentAgregator;
  10167. }());
  10168. var InternalPromise = /** @class */ (function () {
  10169. function InternalPromise(resolver) {
  10170. var _this = this;
  10171. this._state = PromiseStates.Pending;
  10172. this._children = new Array();
  10173. this._rejectWasConsumed = false;
  10174. if (!resolver) {
  10175. return;
  10176. }
  10177. try {
  10178. resolver(function (value) {
  10179. _this._resolve(value);
  10180. }, function (reason) {
  10181. _this._reject(reason);
  10182. });
  10183. }
  10184. catch (e) {
  10185. this._reject(e);
  10186. }
  10187. }
  10188. Object.defineProperty(InternalPromise.prototype, "_result", {
  10189. get: function () {
  10190. return this._resultValue;
  10191. },
  10192. set: function (value) {
  10193. this._resultValue = value;
  10194. if (this._parent && this._parent._result === undefined) {
  10195. this._parent._result = value;
  10196. }
  10197. },
  10198. enumerable: true,
  10199. configurable: true
  10200. });
  10201. InternalPromise.prototype.catch = function (onRejected) {
  10202. return this.then(undefined, onRejected);
  10203. };
  10204. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10205. var _this = this;
  10206. var newPromise = new InternalPromise();
  10207. newPromise._onFulfilled = onFulfilled;
  10208. newPromise._onRejected = onRejected;
  10209. // Composition
  10210. this._children.push(newPromise);
  10211. newPromise._parent = this;
  10212. if (this._state !== PromiseStates.Pending) {
  10213. BABYLON.Tools.SetImmediate(function () {
  10214. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10215. var returnedValue = newPromise._resolve(_this._result);
  10216. if (returnedValue !== undefined && returnedValue !== null) {
  10217. if (returnedValue._state !== undefined) {
  10218. var returnedPromise = returnedValue;
  10219. newPromise._children.push(returnedPromise);
  10220. returnedPromise._parent = newPromise;
  10221. newPromise = returnedPromise;
  10222. }
  10223. else {
  10224. newPromise._result = returnedValue;
  10225. }
  10226. }
  10227. }
  10228. else {
  10229. newPromise._reject(_this._reason);
  10230. }
  10231. });
  10232. }
  10233. return newPromise;
  10234. };
  10235. InternalPromise.prototype._moveChildren = function (children) {
  10236. var _this = this;
  10237. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10238. this._children.forEach(function (child) {
  10239. child._parent = _this;
  10240. });
  10241. if (this._state === PromiseStates.Fulfilled) {
  10242. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10243. var child = _b[_i];
  10244. child._resolve(this._result);
  10245. }
  10246. }
  10247. else if (this._state === PromiseStates.Rejected) {
  10248. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10249. var child = _d[_c];
  10250. child._reject(this._reason);
  10251. }
  10252. }
  10253. var _a;
  10254. };
  10255. InternalPromise.prototype._resolve = function (value) {
  10256. try {
  10257. this._state = PromiseStates.Fulfilled;
  10258. var returnedValue = null;
  10259. if (this._onFulfilled) {
  10260. returnedValue = this._onFulfilled(value);
  10261. }
  10262. if (returnedValue !== undefined && returnedValue !== null) {
  10263. if (returnedValue._state !== undefined) {
  10264. // Transmit children
  10265. var returnedPromise = returnedValue;
  10266. returnedPromise._parent = this;
  10267. returnedPromise._moveChildren(this._children);
  10268. value = returnedPromise._result;
  10269. }
  10270. else {
  10271. value = returnedValue;
  10272. }
  10273. }
  10274. this._result = value;
  10275. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10276. var child = _a[_i];
  10277. child._resolve(value);
  10278. }
  10279. this._children.length = 0;
  10280. delete this._onFulfilled;
  10281. delete this._onRejected;
  10282. }
  10283. catch (e) {
  10284. this._reject(e, true);
  10285. }
  10286. };
  10287. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10288. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10289. this._state = PromiseStates.Rejected;
  10290. this._reason = reason;
  10291. if (this._onRejected && !onLocalThrow) {
  10292. try {
  10293. this._onRejected(reason);
  10294. this._rejectWasConsumed = true;
  10295. }
  10296. catch (e) {
  10297. reason = e;
  10298. }
  10299. }
  10300. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10301. var child = _a[_i];
  10302. if (this._rejectWasConsumed) {
  10303. child._resolve(null);
  10304. }
  10305. else {
  10306. child._reject(reason);
  10307. }
  10308. }
  10309. this._children.length = 0;
  10310. delete this._onFulfilled;
  10311. delete this._onRejected;
  10312. };
  10313. InternalPromise.resolve = function (value) {
  10314. var newPromise = new InternalPromise();
  10315. newPromise._resolve(value);
  10316. return newPromise;
  10317. };
  10318. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10319. promise.then(function (value) {
  10320. agregator.results[index] = value;
  10321. agregator.count++;
  10322. if (agregator.count === agregator.target) {
  10323. agregator.rootPromise._resolve(agregator.results);
  10324. }
  10325. return null;
  10326. }, function (reason) {
  10327. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10328. agregator.rootPromise._reject(reason);
  10329. }
  10330. });
  10331. };
  10332. InternalPromise.all = function (promises) {
  10333. var newPromise = new InternalPromise();
  10334. var agregator = new FulFillmentAgregator();
  10335. agregator.target = promises.length;
  10336. agregator.rootPromise = newPromise;
  10337. if (promises.length) {
  10338. for (var index = 0; index < promises.length; index++) {
  10339. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10340. }
  10341. }
  10342. else {
  10343. newPromise._resolve([]);
  10344. }
  10345. return newPromise;
  10346. };
  10347. InternalPromise.race = function (promises) {
  10348. var newPromise = new InternalPromise();
  10349. if (promises.length) {
  10350. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10351. var promise = promises_1[_i];
  10352. promise.then(function (value) {
  10353. if (newPromise) {
  10354. newPromise._resolve(value);
  10355. newPromise = null;
  10356. }
  10357. return null;
  10358. }, function (reason) {
  10359. if (newPromise) {
  10360. newPromise._reject(reason);
  10361. newPromise = null;
  10362. }
  10363. });
  10364. }
  10365. }
  10366. return newPromise;
  10367. };
  10368. return InternalPromise;
  10369. }());
  10370. /**
  10371. * Helper class that provides a small promise polyfill
  10372. */
  10373. var PromisePolyfill = /** @class */ (function () {
  10374. function PromisePolyfill() {
  10375. }
  10376. /**
  10377. * Static function used to check if the polyfill is required
  10378. * If this is the case then the function will inject the polyfill to window.Promise
  10379. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10380. */
  10381. PromisePolyfill.Apply = function (force) {
  10382. if (force === void 0) { force = false; }
  10383. if (force || typeof Promise === 'undefined') {
  10384. var root = window;
  10385. root.Promise = InternalPromise;
  10386. }
  10387. };
  10388. return PromisePolyfill;
  10389. }());
  10390. BABYLON.PromisePolyfill = PromisePolyfill;
  10391. })(BABYLON || (BABYLON = {}));
  10392. //# sourceMappingURL=babylon.promise.js.map
  10393. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10394. var BABYLON;
  10395. (function (BABYLON) {
  10396. /**
  10397. * Helper class to push actions to a pool of workers.
  10398. */
  10399. var WorkerPool = /** @class */ (function () {
  10400. /**
  10401. * Constructor
  10402. * @param workers Array of workers to use for actions
  10403. */
  10404. function WorkerPool(workers) {
  10405. this._pendingActions = new Array();
  10406. this._workerInfos = workers.map(function (worker) { return ({
  10407. worker: worker,
  10408. active: false
  10409. }); });
  10410. }
  10411. /**
  10412. * Terminates all workers and clears any pending actions.
  10413. */
  10414. WorkerPool.prototype.dispose = function () {
  10415. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10416. var workerInfo = _a[_i];
  10417. workerInfo.worker.terminate();
  10418. }
  10419. delete this._workerInfos;
  10420. delete this._pendingActions;
  10421. };
  10422. /**
  10423. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10424. * pended until a worker has completed its action.
  10425. * @param action The action to perform. Call onComplete when the action is complete.
  10426. */
  10427. WorkerPool.prototype.push = function (action) {
  10428. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10429. var workerInfo = _a[_i];
  10430. if (!workerInfo.active) {
  10431. this._execute(workerInfo, action);
  10432. return;
  10433. }
  10434. }
  10435. this._pendingActions.push(action);
  10436. };
  10437. WorkerPool.prototype._execute = function (workerInfo, action) {
  10438. var _this = this;
  10439. workerInfo.active = true;
  10440. action(workerInfo.worker, function () {
  10441. workerInfo.active = false;
  10442. var nextAction = _this._pendingActions.shift();
  10443. if (nextAction) {
  10444. _this._execute(workerInfo, nextAction);
  10445. }
  10446. });
  10447. };
  10448. return WorkerPool;
  10449. }());
  10450. BABYLON.WorkerPool = WorkerPool;
  10451. })(BABYLON || (BABYLON = {}));
  10452. //# sourceMappingURL=babylon.workerPool.js.map
  10453. var BABYLON;
  10454. (function (BABYLON) {
  10455. /**
  10456. * @hidden
  10457. **/
  10458. var _AlphaState = /** @class */ (function () {
  10459. /**
  10460. * Initializes the state.
  10461. */
  10462. function _AlphaState() {
  10463. this._isAlphaBlendDirty = false;
  10464. this._isBlendFunctionParametersDirty = false;
  10465. this._isBlendEquationParametersDirty = false;
  10466. this._isBlendConstantsDirty = false;
  10467. this._alphaBlend = false;
  10468. this._blendFunctionParameters = new Array(4);
  10469. this._blendEquationParameters = new Array(2);
  10470. this._blendConstants = new Array(4);
  10471. this.reset();
  10472. }
  10473. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10474. get: function () {
  10475. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10476. },
  10477. enumerable: true,
  10478. configurable: true
  10479. });
  10480. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10481. get: function () {
  10482. return this._alphaBlend;
  10483. },
  10484. set: function (value) {
  10485. if (this._alphaBlend === value) {
  10486. return;
  10487. }
  10488. this._alphaBlend = value;
  10489. this._isAlphaBlendDirty = true;
  10490. },
  10491. enumerable: true,
  10492. configurable: true
  10493. });
  10494. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10495. if (this._blendConstants[0] === r &&
  10496. this._blendConstants[1] === g &&
  10497. this._blendConstants[2] === b &&
  10498. this._blendConstants[3] === a) {
  10499. return;
  10500. }
  10501. this._blendConstants[0] = r;
  10502. this._blendConstants[1] = g;
  10503. this._blendConstants[2] = b;
  10504. this._blendConstants[3] = a;
  10505. this._isBlendConstantsDirty = true;
  10506. };
  10507. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10508. if (this._blendFunctionParameters[0] === value0 &&
  10509. this._blendFunctionParameters[1] === value1 &&
  10510. this._blendFunctionParameters[2] === value2 &&
  10511. this._blendFunctionParameters[3] === value3) {
  10512. return;
  10513. }
  10514. this._blendFunctionParameters[0] = value0;
  10515. this._blendFunctionParameters[1] = value1;
  10516. this._blendFunctionParameters[2] = value2;
  10517. this._blendFunctionParameters[3] = value3;
  10518. this._isBlendFunctionParametersDirty = true;
  10519. };
  10520. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10521. if (this._blendEquationParameters[0] === rgb &&
  10522. this._blendEquationParameters[1] === alpha) {
  10523. return;
  10524. }
  10525. this._blendEquationParameters[0] = rgb;
  10526. this._blendEquationParameters[1] = alpha;
  10527. this._isBlendEquationParametersDirty = true;
  10528. };
  10529. _AlphaState.prototype.reset = function () {
  10530. this._alphaBlend = false;
  10531. this._blendFunctionParameters[0] = null;
  10532. this._blendFunctionParameters[1] = null;
  10533. this._blendFunctionParameters[2] = null;
  10534. this._blendFunctionParameters[3] = null;
  10535. this._blendEquationParameters[0] = null;
  10536. this._blendEquationParameters[1] = null;
  10537. this._blendConstants[0] = null;
  10538. this._blendConstants[1] = null;
  10539. this._blendConstants[2] = null;
  10540. this._blendConstants[3] = null;
  10541. this._isAlphaBlendDirty = true;
  10542. this._isBlendFunctionParametersDirty = false;
  10543. this._isBlendEquationParametersDirty = false;
  10544. this._isBlendConstantsDirty = false;
  10545. };
  10546. _AlphaState.prototype.apply = function (gl) {
  10547. if (!this.isDirty) {
  10548. return;
  10549. }
  10550. // Alpha blend
  10551. if (this._isAlphaBlendDirty) {
  10552. if (this._alphaBlend) {
  10553. gl.enable(gl.BLEND);
  10554. }
  10555. else {
  10556. gl.disable(gl.BLEND);
  10557. }
  10558. this._isAlphaBlendDirty = false;
  10559. }
  10560. // Alpha function
  10561. if (this._isBlendFunctionParametersDirty) {
  10562. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10563. this._isBlendFunctionParametersDirty = false;
  10564. }
  10565. // Alpha equation
  10566. if (this._isBlendEquationParametersDirty) {
  10567. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10568. this._isBlendEquationParametersDirty = false;
  10569. }
  10570. // Constants
  10571. if (this._isBlendConstantsDirty) {
  10572. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10573. this._isBlendConstantsDirty = false;
  10574. }
  10575. };
  10576. return _AlphaState;
  10577. }());
  10578. BABYLON._AlphaState = _AlphaState;
  10579. })(BABYLON || (BABYLON = {}));
  10580. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10581. var BABYLON;
  10582. (function (BABYLON) {
  10583. /**
  10584. * @hidden
  10585. **/
  10586. var _DepthCullingState = /** @class */ (function () {
  10587. /**
  10588. * Initializes the state.
  10589. */
  10590. function _DepthCullingState() {
  10591. this._isDepthTestDirty = false;
  10592. this._isDepthMaskDirty = false;
  10593. this._isDepthFuncDirty = false;
  10594. this._isCullFaceDirty = false;
  10595. this._isCullDirty = false;
  10596. this._isZOffsetDirty = false;
  10597. this._isFrontFaceDirty = false;
  10598. this.reset();
  10599. }
  10600. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10601. get: function () {
  10602. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10603. },
  10604. enumerable: true,
  10605. configurable: true
  10606. });
  10607. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10608. get: function () {
  10609. return this._zOffset;
  10610. },
  10611. set: function (value) {
  10612. if (this._zOffset === value) {
  10613. return;
  10614. }
  10615. this._zOffset = value;
  10616. this._isZOffsetDirty = true;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10622. get: function () {
  10623. return this._cullFace;
  10624. },
  10625. set: function (value) {
  10626. if (this._cullFace === value) {
  10627. return;
  10628. }
  10629. this._cullFace = value;
  10630. this._isCullFaceDirty = true;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10636. get: function () {
  10637. return this._cull;
  10638. },
  10639. set: function (value) {
  10640. if (this._cull === value) {
  10641. return;
  10642. }
  10643. this._cull = value;
  10644. this._isCullDirty = true;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10650. get: function () {
  10651. return this._depthFunc;
  10652. },
  10653. set: function (value) {
  10654. if (this._depthFunc === value) {
  10655. return;
  10656. }
  10657. this._depthFunc = value;
  10658. this._isDepthFuncDirty = true;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10664. get: function () {
  10665. return this._depthMask;
  10666. },
  10667. set: function (value) {
  10668. if (this._depthMask === value) {
  10669. return;
  10670. }
  10671. this._depthMask = value;
  10672. this._isDepthMaskDirty = true;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10678. get: function () {
  10679. return this._depthTest;
  10680. },
  10681. set: function (value) {
  10682. if (this._depthTest === value) {
  10683. return;
  10684. }
  10685. this._depthTest = value;
  10686. this._isDepthTestDirty = true;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10692. get: function () {
  10693. return this._frontFace;
  10694. },
  10695. set: function (value) {
  10696. if (this._frontFace === value) {
  10697. return;
  10698. }
  10699. this._frontFace = value;
  10700. this._isFrontFaceDirty = true;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. _DepthCullingState.prototype.reset = function () {
  10706. this._depthMask = true;
  10707. this._depthTest = true;
  10708. this._depthFunc = null;
  10709. this._cullFace = null;
  10710. this._cull = null;
  10711. this._zOffset = 0;
  10712. this._frontFace = null;
  10713. this._isDepthTestDirty = true;
  10714. this._isDepthMaskDirty = true;
  10715. this._isDepthFuncDirty = false;
  10716. this._isCullFaceDirty = false;
  10717. this._isCullDirty = false;
  10718. this._isZOffsetDirty = false;
  10719. this._isFrontFaceDirty = false;
  10720. };
  10721. _DepthCullingState.prototype.apply = function (gl) {
  10722. if (!this.isDirty) {
  10723. return;
  10724. }
  10725. // Cull
  10726. if (this._isCullDirty) {
  10727. if (this.cull) {
  10728. gl.enable(gl.CULL_FACE);
  10729. }
  10730. else {
  10731. gl.disable(gl.CULL_FACE);
  10732. }
  10733. this._isCullDirty = false;
  10734. }
  10735. // Cull face
  10736. if (this._isCullFaceDirty) {
  10737. gl.cullFace(this.cullFace);
  10738. this._isCullFaceDirty = false;
  10739. }
  10740. // Depth mask
  10741. if (this._isDepthMaskDirty) {
  10742. gl.depthMask(this.depthMask);
  10743. this._isDepthMaskDirty = false;
  10744. }
  10745. // Depth test
  10746. if (this._isDepthTestDirty) {
  10747. if (this.depthTest) {
  10748. gl.enable(gl.DEPTH_TEST);
  10749. }
  10750. else {
  10751. gl.disable(gl.DEPTH_TEST);
  10752. }
  10753. this._isDepthTestDirty = false;
  10754. }
  10755. // Depth func
  10756. if (this._isDepthFuncDirty) {
  10757. gl.depthFunc(this.depthFunc);
  10758. this._isDepthFuncDirty = false;
  10759. }
  10760. // zOffset
  10761. if (this._isZOffsetDirty) {
  10762. if (this.zOffset) {
  10763. gl.enable(gl.POLYGON_OFFSET_FILL);
  10764. gl.polygonOffset(this.zOffset, 0);
  10765. }
  10766. else {
  10767. gl.disable(gl.POLYGON_OFFSET_FILL);
  10768. }
  10769. this._isZOffsetDirty = false;
  10770. }
  10771. // Front face
  10772. if (this._isFrontFaceDirty) {
  10773. gl.frontFace(this.frontFace);
  10774. this._isFrontFaceDirty = false;
  10775. }
  10776. };
  10777. return _DepthCullingState;
  10778. }());
  10779. BABYLON._DepthCullingState = _DepthCullingState;
  10780. })(BABYLON || (BABYLON = {}));
  10781. //# sourceMappingURL=babylon.depthCullingState.js.map
  10782. var BABYLON;
  10783. (function (BABYLON) {
  10784. /**
  10785. * @hidden
  10786. **/
  10787. var _StencilState = /** @class */ (function () {
  10788. function _StencilState() {
  10789. this._isStencilTestDirty = false;
  10790. this._isStencilMaskDirty = false;
  10791. this._isStencilFuncDirty = false;
  10792. this._isStencilOpDirty = false;
  10793. this.reset();
  10794. }
  10795. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10796. get: function () {
  10797. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10803. get: function () {
  10804. return this._stencilFunc;
  10805. },
  10806. set: function (value) {
  10807. if (this._stencilFunc === value) {
  10808. return;
  10809. }
  10810. this._stencilFunc = value;
  10811. this._isStencilFuncDirty = true;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10817. get: function () {
  10818. return this._stencilFuncRef;
  10819. },
  10820. set: function (value) {
  10821. if (this._stencilFuncRef === value) {
  10822. return;
  10823. }
  10824. this._stencilFuncRef = value;
  10825. this._isStencilFuncDirty = true;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10831. get: function () {
  10832. return this._stencilFuncMask;
  10833. },
  10834. set: function (value) {
  10835. if (this._stencilFuncMask === value) {
  10836. return;
  10837. }
  10838. this._stencilFuncMask = value;
  10839. this._isStencilFuncDirty = true;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10845. get: function () {
  10846. return this._stencilOpStencilFail;
  10847. },
  10848. set: function (value) {
  10849. if (this._stencilOpStencilFail === value) {
  10850. return;
  10851. }
  10852. this._stencilOpStencilFail = value;
  10853. this._isStencilOpDirty = true;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10859. get: function () {
  10860. return this._stencilOpDepthFail;
  10861. },
  10862. set: function (value) {
  10863. if (this._stencilOpDepthFail === value) {
  10864. return;
  10865. }
  10866. this._stencilOpDepthFail = value;
  10867. this._isStencilOpDirty = true;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10873. get: function () {
  10874. return this._stencilOpStencilDepthPass;
  10875. },
  10876. set: function (value) {
  10877. if (this._stencilOpStencilDepthPass === value) {
  10878. return;
  10879. }
  10880. this._stencilOpStencilDepthPass = value;
  10881. this._isStencilOpDirty = true;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10887. get: function () {
  10888. return this._stencilMask;
  10889. },
  10890. set: function (value) {
  10891. if (this._stencilMask === value) {
  10892. return;
  10893. }
  10894. this._stencilMask = value;
  10895. this._isStencilMaskDirty = true;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10901. get: function () {
  10902. return this._stencilTest;
  10903. },
  10904. set: function (value) {
  10905. if (this._stencilTest === value) {
  10906. return;
  10907. }
  10908. this._stencilTest = value;
  10909. this._isStencilTestDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. _StencilState.prototype.reset = function () {
  10915. this._stencilTest = false;
  10916. this._stencilMask = 0xFF;
  10917. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10918. this._stencilFuncRef = 1;
  10919. this._stencilFuncMask = 0xFF;
  10920. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10921. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10922. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10923. this._isStencilTestDirty = true;
  10924. this._isStencilMaskDirty = true;
  10925. this._isStencilFuncDirty = true;
  10926. this._isStencilOpDirty = true;
  10927. };
  10928. _StencilState.prototype.apply = function (gl) {
  10929. if (!this.isDirty) {
  10930. return;
  10931. }
  10932. // Stencil test
  10933. if (this._isStencilTestDirty) {
  10934. if (this.stencilTest) {
  10935. gl.enable(gl.STENCIL_TEST);
  10936. }
  10937. else {
  10938. gl.disable(gl.STENCIL_TEST);
  10939. }
  10940. this._isStencilTestDirty = false;
  10941. }
  10942. // Stencil mask
  10943. if (this._isStencilMaskDirty) {
  10944. gl.stencilMask(this.stencilMask);
  10945. this._isStencilMaskDirty = false;
  10946. }
  10947. // Stencil func
  10948. if (this._isStencilFuncDirty) {
  10949. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10950. this._isStencilFuncDirty = false;
  10951. }
  10952. // Stencil op
  10953. if (this._isStencilOpDirty) {
  10954. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10955. this._isStencilOpDirty = false;
  10956. }
  10957. };
  10958. return _StencilState;
  10959. }());
  10960. BABYLON._StencilState = _StencilState;
  10961. })(BABYLON || (BABYLON = {}));
  10962. //# sourceMappingURL=babylon.stencilState.js.map
  10963. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10964. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10965. s = arguments[i];
  10966. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10967. t[p] = s[p];
  10968. }
  10969. return t;
  10970. };
  10971. var BABYLON;
  10972. (function (BABYLON) {
  10973. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10974. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10975. };
  10976. var compileRawShader = function (gl, source, type) {
  10977. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10978. gl.shaderSource(shader, source);
  10979. gl.compileShader(shader);
  10980. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10981. var log = gl.getShaderInfoLog(shader);
  10982. if (log) {
  10983. throw new Error(log);
  10984. }
  10985. }
  10986. if (!shader) {
  10987. throw new Error("Something went wrong while compile the shader.");
  10988. }
  10989. return shader;
  10990. };
  10991. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10992. var magFilter = gl.NEAREST;
  10993. var minFilter = gl.NEAREST;
  10994. switch (samplingMode) {
  10995. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10996. magFilter = gl.LINEAR;
  10997. if (generateMipMaps) {
  10998. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10999. }
  11000. else {
  11001. minFilter = gl.LINEAR;
  11002. }
  11003. break;
  11004. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11005. magFilter = gl.LINEAR;
  11006. if (generateMipMaps) {
  11007. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11008. }
  11009. else {
  11010. minFilter = gl.LINEAR;
  11011. }
  11012. break;
  11013. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11014. magFilter = gl.NEAREST;
  11015. if (generateMipMaps) {
  11016. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11017. }
  11018. else {
  11019. minFilter = gl.NEAREST;
  11020. }
  11021. break;
  11022. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11023. magFilter = gl.NEAREST;
  11024. if (generateMipMaps) {
  11025. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11026. }
  11027. else {
  11028. minFilter = gl.NEAREST;
  11029. }
  11030. break;
  11031. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11032. magFilter = gl.NEAREST;
  11033. if (generateMipMaps) {
  11034. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11035. }
  11036. else {
  11037. minFilter = gl.LINEAR;
  11038. }
  11039. break;
  11040. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11041. magFilter = gl.NEAREST;
  11042. if (generateMipMaps) {
  11043. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11044. }
  11045. else {
  11046. minFilter = gl.LINEAR;
  11047. }
  11048. break;
  11049. case BABYLON.Texture.NEAREST_LINEAR:
  11050. magFilter = gl.NEAREST;
  11051. minFilter = gl.LINEAR;
  11052. break;
  11053. case BABYLON.Texture.NEAREST_NEAREST:
  11054. magFilter = gl.NEAREST;
  11055. minFilter = gl.NEAREST;
  11056. break;
  11057. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11058. magFilter = gl.LINEAR;
  11059. if (generateMipMaps) {
  11060. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11061. }
  11062. else {
  11063. minFilter = gl.NEAREST;
  11064. }
  11065. break;
  11066. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11067. magFilter = gl.LINEAR;
  11068. if (generateMipMaps) {
  11069. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11070. }
  11071. else {
  11072. minFilter = gl.NEAREST;
  11073. }
  11074. break;
  11075. case BABYLON.Texture.LINEAR_LINEAR:
  11076. magFilter = gl.LINEAR;
  11077. minFilter = gl.LINEAR;
  11078. break;
  11079. case BABYLON.Texture.LINEAR_NEAREST:
  11080. magFilter = gl.LINEAR;
  11081. minFilter = gl.NEAREST;
  11082. break;
  11083. }
  11084. return {
  11085. min: minFilter,
  11086. mag: magFilter
  11087. };
  11088. };
  11089. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11090. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11091. var img;
  11092. var onload = function () {
  11093. loadedImages[index] = img;
  11094. loadedImages._internalCount++;
  11095. if (scene) {
  11096. scene._removePendingData(img);
  11097. }
  11098. if (loadedImages._internalCount === 6) {
  11099. onfinish(loadedImages);
  11100. }
  11101. };
  11102. var onerror = function (message, exception) {
  11103. if (scene) {
  11104. scene._removePendingData(img);
  11105. }
  11106. if (onErrorCallBack) {
  11107. onErrorCallBack(message, exception);
  11108. }
  11109. };
  11110. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11111. if (scene) {
  11112. scene._addPendingData(img);
  11113. }
  11114. };
  11115. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11116. if (onError === void 0) { onError = null; }
  11117. var loadedImages = [];
  11118. loadedImages._internalCount = 0;
  11119. for (var index = 0; index < 6; index++) {
  11120. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11121. }
  11122. };
  11123. var BufferPointer = /** @class */ (function () {
  11124. function BufferPointer() {
  11125. }
  11126. return BufferPointer;
  11127. }());
  11128. /**
  11129. * Interface for attribute information associated with buffer instanciation
  11130. */
  11131. var InstancingAttributeInfo = /** @class */ (function () {
  11132. function InstancingAttributeInfo() {
  11133. }
  11134. return InstancingAttributeInfo;
  11135. }());
  11136. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11137. /**
  11138. * Define options used to create a render target texture
  11139. */
  11140. var RenderTargetCreationOptions = /** @class */ (function () {
  11141. function RenderTargetCreationOptions() {
  11142. }
  11143. return RenderTargetCreationOptions;
  11144. }());
  11145. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11146. /**
  11147. * Define options used to create a depth texture
  11148. */
  11149. var DepthTextureCreationOptions = /** @class */ (function () {
  11150. function DepthTextureCreationOptions() {
  11151. }
  11152. return DepthTextureCreationOptions;
  11153. }());
  11154. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11155. /**
  11156. * Class used to describe the capabilities of the engine relatively to the current browser
  11157. */
  11158. var EngineCapabilities = /** @class */ (function () {
  11159. function EngineCapabilities() {
  11160. }
  11161. return EngineCapabilities;
  11162. }());
  11163. BABYLON.EngineCapabilities = EngineCapabilities;
  11164. /**
  11165. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11166. */
  11167. var Engine = /** @class */ (function () {
  11168. /**
  11169. * Creates a new engine
  11170. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11171. * @param antialias defines enable antialiasing (default: false)
  11172. * @param options defines further options to be sent to the getContext() function
  11173. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11174. */
  11175. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11176. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11177. var _this = this;
  11178. // Public members
  11179. /**
  11180. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11181. */
  11182. this.forcePOTTextures = false;
  11183. /**
  11184. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11185. */
  11186. this.isFullscreen = false;
  11187. /**
  11188. * Gets a boolean indicating if the pointer is currently locked
  11189. */
  11190. this.isPointerLock = false;
  11191. /**
  11192. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11193. */
  11194. this.cullBackFaces = true;
  11195. /**
  11196. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11197. */
  11198. this.renderEvenInBackground = true;
  11199. /**
  11200. * Gets or sets a boolean indicating that cache can be kept between frames
  11201. */
  11202. this.preventCacheWipeBetweenFrames = false;
  11203. /**
  11204. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11205. **/
  11206. this.enableOfflineSupport = false;
  11207. /**
  11208. * 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)
  11209. **/
  11210. this.disableManifestCheck = false;
  11211. /**
  11212. * Gets the list of created scenes
  11213. */
  11214. this.scenes = new Array();
  11215. /**
  11216. * Gets the list of created postprocesses
  11217. */
  11218. this.postProcesses = new Array();
  11219. // Observables
  11220. /**
  11221. * Observable event triggered each time the rendering canvas is resized
  11222. */
  11223. this.onResizeObservable = new BABYLON.Observable();
  11224. /**
  11225. * Observable event triggered each time the canvas loses focus
  11226. */
  11227. this.onCanvasBlurObservable = new BABYLON.Observable();
  11228. /**
  11229. * Observable event triggered each time the canvas gains focus
  11230. */
  11231. this.onCanvasFocusObservable = new BABYLON.Observable();
  11232. /**
  11233. * Observable event triggered each time the canvas receives pointerout event
  11234. */
  11235. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11236. /**
  11237. * Observable event triggered before each texture is initialized
  11238. */
  11239. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11240. //WebVR
  11241. this._vrDisplay = undefined;
  11242. this._vrSupported = false;
  11243. this._vrExclusivePointerMode = false;
  11244. // Uniform buffers list
  11245. /**
  11246. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11247. */
  11248. this.disableUniformBuffers = false;
  11249. /** @hidden */
  11250. this._uniformBuffers = new Array();
  11251. // Observables
  11252. /**
  11253. * Observable raised when the engine begins a new frame
  11254. */
  11255. this.onBeginFrameObservable = new BABYLON.Observable();
  11256. /**
  11257. * Observable raised when the engine ends the current frame
  11258. */
  11259. this.onEndFrameObservable = new BABYLON.Observable();
  11260. /**
  11261. * Observable raised when the engine is about to compile a shader
  11262. */
  11263. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11264. /**
  11265. * Observable raised when the engine has jsut compiled a shader
  11266. */
  11267. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11268. this._windowIsBackground = false;
  11269. this._webGLVersion = 1.0;
  11270. /** @hidden */
  11271. this._badOS = false;
  11272. /** @hidden */
  11273. this._badDesktopOS = false;
  11274. /**
  11275. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11276. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11277. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11278. */
  11279. this.disableTextureBindingOptimization = false;
  11280. /**
  11281. * Observable signaled when VR display mode changes
  11282. */
  11283. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11284. /**
  11285. * Observable signaled when VR request present is complete
  11286. */
  11287. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11288. /**
  11289. * Observable signaled when VR request present starts
  11290. */
  11291. this.onVRRequestPresentStart = new BABYLON.Observable();
  11292. this._colorWrite = true;
  11293. /** @hidden */
  11294. this._drawCalls = new BABYLON.PerfCounter();
  11295. /** @hidden */
  11296. this._textureCollisions = new BABYLON.PerfCounter();
  11297. this._renderingQueueLaunched = false;
  11298. this._activeRenderLoops = new Array();
  11299. // Deterministic lockstepMaxSteps
  11300. this._deterministicLockstep = false;
  11301. this._lockstepMaxSteps = 4;
  11302. // Lost context
  11303. /**
  11304. * Observable signaled when a context lost event is raised
  11305. */
  11306. this.onContextLostObservable = new BABYLON.Observable();
  11307. /**
  11308. * Observable signaled when a context restored event is raised
  11309. */
  11310. this.onContextRestoredObservable = new BABYLON.Observable();
  11311. this._contextWasLost = false;
  11312. this._doNotHandleContextLost = false;
  11313. // FPS
  11314. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11315. this._fps = 60;
  11316. this._deltaTime = 0;
  11317. /**
  11318. * Turn this value on if you want to pause FPS computation when in background
  11319. */
  11320. this.disablePerformanceMonitorInBackground = false;
  11321. // States
  11322. /** @hidden */
  11323. this._depthCullingState = new BABYLON._DepthCullingState();
  11324. /** @hidden */
  11325. this._stencilState = new BABYLON._StencilState();
  11326. /** @hidden */
  11327. this._alphaState = new BABYLON._AlphaState();
  11328. /** @hidden */
  11329. this._alphaMode = Engine.ALPHA_DISABLE;
  11330. // Cache
  11331. this._internalTexturesCache = new Array();
  11332. /** @hidden */
  11333. this._activeChannel = 0;
  11334. this._currentTextureChannel = -1;
  11335. /** @hidden */
  11336. this._boundTexturesCache = {};
  11337. this._compiledEffects = {};
  11338. this._vertexAttribArraysEnabled = [];
  11339. this._uintIndicesCurrentlySet = false;
  11340. this._currentBoundBuffer = new Array();
  11341. this._currentBufferPointers = new Array();
  11342. this._currentInstanceLocations = new Array();
  11343. this._currentInstanceBuffers = new Array();
  11344. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11345. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11346. this._vaoRecordInProgress = false;
  11347. this._mustWipeVertexAttributes = false;
  11348. this._nextFreeTextureSlots = new Array();
  11349. this._maxSimultaneousTextures = 0;
  11350. this._activeRequests = new Array();
  11351. // Hardware supported Compressed Textures
  11352. this._texturesSupported = new Array();
  11353. /**
  11354. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11355. */
  11356. this.premultipliedAlpha = true;
  11357. this._onVRFullScreenTriggered = function () {
  11358. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11359. //get the old size before we change
  11360. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11361. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11362. //get the width and height, change the render size
  11363. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11364. _this.setHardwareScalingLevel(1);
  11365. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11366. }
  11367. else {
  11368. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11369. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11370. }
  11371. };
  11372. this._boundUniforms = {};
  11373. // Register promises
  11374. BABYLON.PromisePolyfill.Apply();
  11375. var canvas = null;
  11376. Engine.Instances.push(this);
  11377. if (!canvasOrContext) {
  11378. return;
  11379. }
  11380. options = options || {};
  11381. if (canvasOrContext.getContext) {
  11382. canvas = canvasOrContext;
  11383. this._renderingCanvas = canvas;
  11384. if (antialias != null) {
  11385. options.antialias = antialias;
  11386. }
  11387. if (options.deterministicLockstep === undefined) {
  11388. options.deterministicLockstep = false;
  11389. }
  11390. if (options.lockstepMaxSteps === undefined) {
  11391. options.lockstepMaxSteps = 4;
  11392. }
  11393. if (options.preserveDrawingBuffer === undefined) {
  11394. options.preserveDrawingBuffer = false;
  11395. }
  11396. if (options.audioEngine === undefined) {
  11397. options.audioEngine = true;
  11398. }
  11399. if (options.stencil === undefined) {
  11400. options.stencil = true;
  11401. }
  11402. if (options.premultipliedAlpha === false) {
  11403. this.premultipliedAlpha = false;
  11404. }
  11405. this._deterministicLockstep = options.deterministicLockstep;
  11406. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11407. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11408. // Exceptions
  11409. if (navigator && navigator.userAgent) {
  11410. var ua = navigator.userAgent;
  11411. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11412. var exception = _a[_i];
  11413. var key = exception.key;
  11414. var targets = exception.targets;
  11415. if (ua.indexOf(key) > -1) {
  11416. if (exception.capture && exception.captureConstraint) {
  11417. var capture = exception.capture;
  11418. var constraint = exception.captureConstraint;
  11419. var regex = new RegExp(capture);
  11420. var matches = regex.exec(ua);
  11421. if (matches && matches.length > 0) {
  11422. var capturedValue = parseInt(matches[matches.length - 1]);
  11423. if (capturedValue >= constraint) {
  11424. continue;
  11425. }
  11426. }
  11427. }
  11428. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11429. var target = targets_1[_b];
  11430. switch (target) {
  11431. case "uniformBuffer":
  11432. this.disableUniformBuffers = true;
  11433. break;
  11434. case "textureBindingOptimization":
  11435. this.disableTextureBindingOptimization = true;
  11436. break;
  11437. }
  11438. }
  11439. }
  11440. }
  11441. }
  11442. // GL
  11443. if (!options.disableWebGL2Support) {
  11444. try {
  11445. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11446. if (this._gl) {
  11447. this._webGLVersion = 2.0;
  11448. }
  11449. }
  11450. catch (e) {
  11451. // Do nothing
  11452. }
  11453. }
  11454. if (!this._gl) {
  11455. if (!canvas) {
  11456. throw new Error("The provided canvas is null or undefined.");
  11457. }
  11458. try {
  11459. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11460. }
  11461. catch (e) {
  11462. throw new Error("WebGL not supported");
  11463. }
  11464. }
  11465. if (!this._gl) {
  11466. throw new Error("WebGL not supported");
  11467. }
  11468. this._onCanvasFocus = function () {
  11469. _this.onCanvasFocusObservable.notifyObservers(_this);
  11470. };
  11471. this._onCanvasBlur = function () {
  11472. _this.onCanvasBlurObservable.notifyObservers(_this);
  11473. };
  11474. canvas.addEventListener("focus", this._onCanvasFocus);
  11475. canvas.addEventListener("blur", this._onCanvasBlur);
  11476. this._onBlur = function () {
  11477. if (_this.disablePerformanceMonitorInBackground) {
  11478. _this._performanceMonitor.disable();
  11479. }
  11480. _this._windowIsBackground = true;
  11481. };
  11482. this._onFocus = function () {
  11483. if (_this.disablePerformanceMonitorInBackground) {
  11484. _this._performanceMonitor.enable();
  11485. }
  11486. _this._windowIsBackground = false;
  11487. };
  11488. this._onCanvasPointerOut = function (ev) {
  11489. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11490. };
  11491. window.addEventListener("blur", this._onBlur);
  11492. window.addEventListener("focus", this._onFocus);
  11493. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11494. // Context lost
  11495. if (!this._doNotHandleContextLost) {
  11496. this._onContextLost = function (evt) {
  11497. evt.preventDefault();
  11498. _this._contextWasLost = true;
  11499. BABYLON.Tools.Warn("WebGL context lost.");
  11500. _this.onContextLostObservable.notifyObservers(_this);
  11501. };
  11502. this._onContextRestored = function (evt) {
  11503. // Adding a timeout to avoid race condition at browser level
  11504. setTimeout(function () {
  11505. // Rebuild gl context
  11506. _this._initGLContext();
  11507. // Rebuild effects
  11508. _this._rebuildEffects();
  11509. // Rebuild textures
  11510. _this._rebuildInternalTextures();
  11511. // Rebuild buffers
  11512. _this._rebuildBuffers();
  11513. // Cache
  11514. _this.wipeCaches(true);
  11515. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11516. _this.onContextRestoredObservable.notifyObservers(_this);
  11517. _this._contextWasLost = false;
  11518. }, 0);
  11519. };
  11520. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11521. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11522. }
  11523. }
  11524. else {
  11525. this._gl = canvasOrContext;
  11526. this._renderingCanvas = this._gl.canvas;
  11527. if (this._gl.renderbufferStorageMultisample) {
  11528. this._webGLVersion = 2.0;
  11529. }
  11530. options.stencil = this._gl.getContextAttributes().stencil;
  11531. }
  11532. // Viewport
  11533. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11534. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11535. this.resize();
  11536. this._isStencilEnable = options.stencil ? true : false;
  11537. this._initGLContext();
  11538. if (canvas) {
  11539. // Fullscreen
  11540. this._onFullscreenChange = function () {
  11541. if (document.fullscreen !== undefined) {
  11542. _this.isFullscreen = document.fullscreen;
  11543. }
  11544. else if (document.mozFullScreen !== undefined) {
  11545. _this.isFullscreen = document.mozFullScreen;
  11546. }
  11547. else if (document.webkitIsFullScreen !== undefined) {
  11548. _this.isFullscreen = document.webkitIsFullScreen;
  11549. }
  11550. else if (document.msIsFullScreen !== undefined) {
  11551. _this.isFullscreen = document.msIsFullScreen;
  11552. }
  11553. // Pointer lock
  11554. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11555. canvas.requestPointerLock = canvas.requestPointerLock ||
  11556. canvas.msRequestPointerLock ||
  11557. canvas.mozRequestPointerLock ||
  11558. canvas.webkitRequestPointerLock;
  11559. if (canvas.requestPointerLock) {
  11560. canvas.requestPointerLock();
  11561. }
  11562. }
  11563. };
  11564. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11565. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11566. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11567. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11568. // Pointer lock
  11569. this._onPointerLockChange = function () {
  11570. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11571. document.webkitPointerLockElement === canvas ||
  11572. document.msPointerLockElement === canvas ||
  11573. document.pointerLockElement === canvas);
  11574. };
  11575. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11576. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11577. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11578. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11579. this._onVRDisplayPointerRestricted = function () {
  11580. if (canvas) {
  11581. canvas.requestPointerLock();
  11582. }
  11583. };
  11584. this._onVRDisplayPointerUnrestricted = function () {
  11585. document.exitPointerLock();
  11586. };
  11587. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11588. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11589. }
  11590. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11591. Engine.audioEngine = new BABYLON.AudioEngine();
  11592. }
  11593. // Prepare buffer pointers
  11594. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11595. this._currentBufferPointers[i] = new BufferPointer();
  11596. }
  11597. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11598. // Load WebVR Devices
  11599. if (options.autoEnableWebVR) {
  11600. this.initWebVR();
  11601. }
  11602. // Detect if we are running on a faulty buggy OS.
  11603. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11604. // Detect if we are running on a faulty buggy desktop OS.
  11605. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11606. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11607. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11608. }
  11609. Object.defineProperty(Engine, "LastCreatedEngine", {
  11610. /**
  11611. * Gets the latest created engine
  11612. */
  11613. get: function () {
  11614. if (Engine.Instances.length === 0) {
  11615. return null;
  11616. }
  11617. return Engine.Instances[Engine.Instances.length - 1];
  11618. },
  11619. enumerable: true,
  11620. configurable: true
  11621. });
  11622. Object.defineProperty(Engine, "LastCreatedScene", {
  11623. /**
  11624. * Gets the latest created scene
  11625. */
  11626. get: function () {
  11627. var lastCreatedEngine = Engine.LastCreatedEngine;
  11628. if (!lastCreatedEngine) {
  11629. return null;
  11630. }
  11631. if (lastCreatedEngine.scenes.length === 0) {
  11632. return null;
  11633. }
  11634. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11635. },
  11636. enumerable: true,
  11637. configurable: true
  11638. });
  11639. /**
  11640. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11641. * @param flag defines which part of the materials must be marked as dirty
  11642. * @param predicate defines a predicate used to filter which materials should be affected
  11643. */
  11644. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11645. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11646. var engine = Engine.Instances[engineIndex];
  11647. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11648. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11649. }
  11650. }
  11651. };
  11652. Object.defineProperty(Engine, "NEVER", {
  11653. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11654. get: function () {
  11655. return Engine._NEVER;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Engine, "ALWAYS", {
  11661. /** 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 */
  11662. get: function () {
  11663. return Engine._ALWAYS;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "LESS", {
  11669. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11670. get: function () {
  11671. return Engine._LESS;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Engine, "EQUAL", {
  11677. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11678. get: function () {
  11679. return Engine._EQUAL;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine, "LEQUAL", {
  11685. /** 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 */
  11686. get: function () {
  11687. return Engine._LEQUAL;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Engine, "GREATER", {
  11693. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11694. get: function () {
  11695. return Engine._GREATER;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine, "GEQUAL", {
  11701. /** 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 */
  11702. get: function () {
  11703. return Engine._GEQUAL;
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Engine, "NOTEQUAL", {
  11709. /** 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 */
  11710. get: function () {
  11711. return Engine._NOTEQUAL;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine, "KEEP", {
  11717. /** Passed to stencilOperation to specify that stencil value must be kept */
  11718. get: function () {
  11719. return Engine._KEEP;
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(Engine, "REPLACE", {
  11725. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11726. get: function () {
  11727. return Engine._REPLACE;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(Engine, "INCR", {
  11733. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11734. get: function () {
  11735. return Engine._INCR;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine, "DECR", {
  11741. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11742. get: function () {
  11743. return Engine._DECR;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine, "INVERT", {
  11749. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11750. get: function () {
  11751. return Engine._INVERT;
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(Engine, "INCR_WRAP", {
  11757. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11758. get: function () {
  11759. return Engine._INCR_WRAP;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Engine, "DECR_WRAP", {
  11765. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11766. get: function () {
  11767. return Engine._DECR_WRAP;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11773. // Alpha
  11774. /** Defines that alpha blending is disabled */
  11775. get: function () {
  11776. return Engine._ALPHA_DISABLE;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11782. /** Defines that alpha blending to SRC + DEST */
  11783. get: function () {
  11784. return Engine._ALPHA_ONEONE;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine, "ALPHA_ADD", {
  11790. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11791. get: function () {
  11792. return Engine._ALPHA_ADD;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11798. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11799. get: function () {
  11800. return Engine._ALPHA_COMBINE;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11806. /** Defines that alpha blending to DEST - SRC * DEST */
  11807. get: function () {
  11808. return Engine._ALPHA_SUBTRACT;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11814. /** Defines that alpha blending to SRC * DEST */
  11815. get: function () {
  11816. return Engine._ALPHA_MULTIPLY;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11822. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11823. get: function () {
  11824. return Engine._ALPHA_MAXIMIZED;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11830. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11831. get: function () {
  11832. return Engine._ALPHA_PREMULTIPLIED;
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11838. /**
  11839. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11840. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11841. */
  11842. get: function () {
  11843. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11849. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11850. get: function () {
  11851. return Engine._ALPHA_INTERPOLATE;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11857. /**
  11858. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11859. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11860. */
  11861. get: function () {
  11862. return Engine._ALPHA_SCREENMODE;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11868. // Delays
  11869. /** Defines that the ressource is not delayed*/
  11870. get: function () {
  11871. return Engine._DELAYLOADSTATE_NONE;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11877. /** Defines that the ressource was successfully delay loaded */
  11878. get: function () {
  11879. return Engine._DELAYLOADSTATE_LOADED;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11885. /** Defines that the ressource is currently delay loading */
  11886. get: function () {
  11887. return Engine._DELAYLOADSTATE_LOADING;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11893. /** Defines that the ressource is delayed and has not started loading */
  11894. get: function () {
  11895. return Engine._DELAYLOADSTATE_NOTLOADED;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11901. /** ALPHA */
  11902. get: function () {
  11903. return Engine._TEXTUREFORMAT_ALPHA;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11909. /** LUMINANCE */
  11910. get: function () {
  11911. return Engine._TEXTUREFORMAT_LUMINANCE;
  11912. },
  11913. enumerable: true,
  11914. configurable: true
  11915. });
  11916. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11917. /**
  11918. * R
  11919. */
  11920. get: function () {
  11921. return Engine._TEXTUREFORMAT_R;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11927. /**
  11928. * RG
  11929. */
  11930. get: function () {
  11931. return Engine._TEXTUREFORMAT_RG;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11937. /** LUMINANCE_ALPHA */
  11938. get: function () {
  11939. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11940. },
  11941. enumerable: true,
  11942. configurable: true
  11943. });
  11944. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11945. /** RGB */
  11946. get: function () {
  11947. return Engine._TEXTUREFORMAT_RGB;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11953. /** RGBA */
  11954. get: function () {
  11955. return Engine._TEXTUREFORMAT_RGBA;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11961. /** UNSIGNED_INT */
  11962. get: function () {
  11963. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11969. /** FLOAT */
  11970. get: function () {
  11971. return Engine._TEXTURETYPE_FLOAT;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11977. /** HALF_FLOAT */
  11978. get: function () {
  11979. return Engine._TEXTURETYPE_HALF_FLOAT;
  11980. },
  11981. enumerable: true,
  11982. configurable: true
  11983. });
  11984. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11985. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11986. get: function () {
  11987. return Engine._SCALEMODE_FLOOR;
  11988. },
  11989. enumerable: true,
  11990. configurable: true
  11991. });
  11992. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11993. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11994. get: function () {
  11995. return Engine._SCALEMODE_NEAREST;
  11996. },
  11997. enumerable: true,
  11998. configurable: true
  11999. });
  12000. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12001. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12002. get: function () {
  12003. return Engine._SCALEMODE_CEILING;
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Object.defineProperty(Engine, "Version", {
  12009. /**
  12010. * Returns the current version of the framework
  12011. */
  12012. get: function () {
  12013. return "3.3.0-alpha.4";
  12014. },
  12015. enumerable: true,
  12016. configurable: true
  12017. });
  12018. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12019. /**
  12020. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12021. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12022. */
  12023. get: function () {
  12024. return this._vrExclusivePointerMode;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12030. /**
  12031. * Gets a boolean indicating that the engine supports uniform buffers
  12032. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12033. */
  12034. get: function () {
  12035. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12041. /**
  12042. * Gets a boolean indicating that only power of 2 textures are supported
  12043. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12044. */
  12045. get: function () {
  12046. return this._webGLVersion < 2 || this.forcePOTTextures;
  12047. },
  12048. enumerable: true,
  12049. configurable: true
  12050. });
  12051. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12052. /**
  12053. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12054. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12055. */
  12056. get: function () {
  12057. return this._doNotHandleContextLost;
  12058. },
  12059. set: function (value) {
  12060. this._doNotHandleContextLost = value;
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12066. /**
  12067. * Gets the performance monitor attached to this engine
  12068. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12069. */
  12070. get: function () {
  12071. return this._performanceMonitor;
  12072. },
  12073. enumerable: true,
  12074. configurable: true
  12075. });
  12076. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12077. /**
  12078. * Gets the list of texture formats supported
  12079. */
  12080. get: function () {
  12081. return this._texturesSupported;
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12087. /**
  12088. * Gets the list of texture formats in use
  12089. */
  12090. get: function () {
  12091. return this._textureFormatInUse;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Engine.prototype, "currentViewport", {
  12097. /**
  12098. * Gets the current viewport
  12099. */
  12100. get: function () {
  12101. return this._cachedViewport;
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12107. /**
  12108. * Gets the default empty texture
  12109. */
  12110. get: function () {
  12111. if (!this._emptyTexture) {
  12112. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12113. }
  12114. return this._emptyTexture;
  12115. },
  12116. enumerable: true,
  12117. configurable: true
  12118. });
  12119. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12120. /**
  12121. * Gets the default empty 3D texture
  12122. */
  12123. get: function () {
  12124. if (!this._emptyTexture3D) {
  12125. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12126. }
  12127. return this._emptyTexture3D;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12133. /**
  12134. * Gets the default empty cube texture
  12135. */
  12136. get: function () {
  12137. if (!this._emptyCubeTexture) {
  12138. var faceData = new Uint8Array(4);
  12139. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12140. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12141. }
  12142. return this._emptyCubeTexture;
  12143. },
  12144. enumerable: true,
  12145. configurable: true
  12146. });
  12147. Engine.prototype._rebuildInternalTextures = function () {
  12148. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12149. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12150. var internalTexture = currentState_1[_i];
  12151. internalTexture._rebuild();
  12152. }
  12153. };
  12154. Engine.prototype._rebuildEffects = function () {
  12155. for (var key in this._compiledEffects) {
  12156. var effect = this._compiledEffects[key];
  12157. effect._prepareEffect();
  12158. }
  12159. BABYLON.Effect.ResetCache();
  12160. };
  12161. Engine.prototype._rebuildBuffers = function () {
  12162. // Index / Vertex
  12163. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12164. var scene = _a[_i];
  12165. scene.resetCachedMaterial();
  12166. scene._rebuildGeometries();
  12167. scene._rebuildTextures();
  12168. }
  12169. // Uniforms
  12170. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12171. var uniformBuffer = _c[_b];
  12172. uniformBuffer._rebuild();
  12173. }
  12174. };
  12175. Engine.prototype._initGLContext = function () {
  12176. // Caps
  12177. this._caps = new EngineCapabilities();
  12178. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12179. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12180. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12181. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12182. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12183. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12184. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12185. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12186. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12187. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12188. // Infos
  12189. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12190. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12191. if (rendererInfo != null) {
  12192. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12193. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12194. }
  12195. if (!this._glVendor) {
  12196. this._glVendor = "Unknown vendor";
  12197. }
  12198. if (!this._glRenderer) {
  12199. this._glRenderer = "Unknown renderer";
  12200. }
  12201. // Constants
  12202. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12203. if (this._gl.RGBA16F !== 0x881A) {
  12204. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12205. }
  12206. if (this._gl.RGBA32F !== 0x8814) {
  12207. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12208. }
  12209. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12210. this._gl.DEPTH24_STENCIL8 = 35056;
  12211. }
  12212. // Extensions
  12213. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12214. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12215. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12216. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12217. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12218. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12219. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12220. 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');
  12221. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12222. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12223. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12224. this._caps.highPrecisionShaderSupported = true;
  12225. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12226. if (this._caps.timerQuery) {
  12227. if (this._webGLVersion === 1) {
  12228. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12229. }
  12230. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12231. }
  12232. // Checks if some of the format renders first to allow the use of webgl inspector.
  12233. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12234. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12235. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12236. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12237. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12238. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12239. if (this._webGLVersion > 1) {
  12240. this._gl.HALF_FLOAT_OES = 0x140B;
  12241. }
  12242. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12243. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12244. // Draw buffers
  12245. if (this._webGLVersion > 1) {
  12246. this._caps.drawBuffersExtension = true;
  12247. }
  12248. else {
  12249. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12250. if (drawBuffersExtension !== null) {
  12251. this._caps.drawBuffersExtension = true;
  12252. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12253. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12254. for (var i = 0; i < 16; i++) {
  12255. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12256. }
  12257. }
  12258. else {
  12259. this._caps.drawBuffersExtension = false;
  12260. }
  12261. }
  12262. // Depth Texture
  12263. if (this._webGLVersion > 1) {
  12264. this._caps.depthTextureExtension = true;
  12265. }
  12266. else {
  12267. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12268. if (depthTextureExtension != null) {
  12269. this._caps.depthTextureExtension = true;
  12270. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12271. }
  12272. }
  12273. // Vertex array object
  12274. if (this._webGLVersion > 1) {
  12275. this._caps.vertexArrayObject = true;
  12276. }
  12277. else {
  12278. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12279. if (vertexArrayObjectExtension != null) {
  12280. this._caps.vertexArrayObject = true;
  12281. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12282. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12283. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12284. }
  12285. else {
  12286. this._caps.vertexArrayObject = false;
  12287. }
  12288. }
  12289. // Instances count
  12290. if (this._webGLVersion > 1) {
  12291. this._caps.instancedArrays = true;
  12292. }
  12293. else {
  12294. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12295. if (instanceExtension != null) {
  12296. this._caps.instancedArrays = true;
  12297. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12298. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12299. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12300. }
  12301. else {
  12302. this._caps.instancedArrays = false;
  12303. }
  12304. }
  12305. // Intelligently add supported compressed formats in order to check for.
  12306. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12307. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12308. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12309. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12310. if (this._caps.astc)
  12311. this.texturesSupported.push('-astc.ktx');
  12312. if (this._caps.s3tc)
  12313. this.texturesSupported.push('-dxt.ktx');
  12314. if (this._caps.pvrtc)
  12315. this.texturesSupported.push('-pvrtc.ktx');
  12316. if (this._caps.etc2)
  12317. this.texturesSupported.push('-etc2.ktx');
  12318. if (this._caps.etc1)
  12319. this.texturesSupported.push('-etc1.ktx');
  12320. if (this._gl.getShaderPrecisionFormat) {
  12321. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12322. if (highp) {
  12323. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12324. }
  12325. }
  12326. // Depth buffer
  12327. this.setDepthBuffer(true);
  12328. this.setDepthFunctionToLessOrEqual();
  12329. this.setDepthWrite(true);
  12330. // Texture maps
  12331. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12332. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12333. this._nextFreeTextureSlots.push(slot);
  12334. }
  12335. };
  12336. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12337. /**
  12338. * Gets version of the current webGL context
  12339. */
  12340. get: function () {
  12341. return this._webGLVersion;
  12342. },
  12343. enumerable: true,
  12344. configurable: true
  12345. });
  12346. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12347. /**
  12348. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12349. */
  12350. get: function () {
  12351. return this._isStencilEnable;
  12352. },
  12353. enumerable: true,
  12354. configurable: true
  12355. });
  12356. Engine.prototype._prepareWorkingCanvas = function () {
  12357. if (this._workingCanvas) {
  12358. return;
  12359. }
  12360. this._workingCanvas = document.createElement("canvas");
  12361. var context = this._workingCanvas.getContext("2d");
  12362. if (context) {
  12363. this._workingContext = context;
  12364. }
  12365. };
  12366. /**
  12367. * Reset the texture cache to empty state
  12368. */
  12369. Engine.prototype.resetTextureCache = function () {
  12370. for (var key in this._boundTexturesCache) {
  12371. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12372. continue;
  12373. }
  12374. var boundTexture = this._boundTexturesCache[key];
  12375. if (boundTexture) {
  12376. this._removeDesignatedSlot(boundTexture);
  12377. }
  12378. this._boundTexturesCache[key] = null;
  12379. }
  12380. if (!this.disableTextureBindingOptimization) {
  12381. this._nextFreeTextureSlots = [];
  12382. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12383. this._nextFreeTextureSlots.push(slot);
  12384. }
  12385. }
  12386. this._currentTextureChannel = -1;
  12387. };
  12388. /**
  12389. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12390. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12391. * @returns true if engine is in deterministic lock step mode
  12392. */
  12393. Engine.prototype.isDeterministicLockStep = function () {
  12394. return this._deterministicLockstep;
  12395. };
  12396. /**
  12397. * Gets the max steps when engine is running in deterministic lock step
  12398. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12399. * @returns the max steps
  12400. */
  12401. Engine.prototype.getLockstepMaxSteps = function () {
  12402. return this._lockstepMaxSteps;
  12403. };
  12404. /**
  12405. * Gets an object containing information about the current webGL context
  12406. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12407. */
  12408. Engine.prototype.getGlInfo = function () {
  12409. return {
  12410. vendor: this._glVendor,
  12411. renderer: this._glRenderer,
  12412. version: this._glVersion
  12413. };
  12414. };
  12415. /**
  12416. * Gets current aspect ratio
  12417. * @param camera defines the camera to use to get the aspect ratio
  12418. * @param useScreen defines if screen size must be used (or the current render target if any)
  12419. * @returns a number defining the aspect ratio
  12420. */
  12421. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12422. if (useScreen === void 0) { useScreen = false; }
  12423. var viewport = camera.viewport;
  12424. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12425. };
  12426. /**
  12427. * Gets current screen aspect ratio
  12428. * @returns a number defining the aspect ratio
  12429. */
  12430. Engine.prototype.getScreenAspectRatio = function () {
  12431. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12432. };
  12433. /**
  12434. * Gets the current render width
  12435. * @param useScreen defines if screen size must be used (or the current render target if any)
  12436. * @returns a number defining the current render width
  12437. */
  12438. Engine.prototype.getRenderWidth = function (useScreen) {
  12439. if (useScreen === void 0) { useScreen = false; }
  12440. if (!useScreen && this._currentRenderTarget) {
  12441. return this._currentRenderTarget.width;
  12442. }
  12443. return this._gl.drawingBufferWidth;
  12444. };
  12445. /**
  12446. * Gets the current render height
  12447. * @param useScreen defines if screen size must be used (or the current render target if any)
  12448. * @returns a number defining the current render height
  12449. */
  12450. Engine.prototype.getRenderHeight = function (useScreen) {
  12451. if (useScreen === void 0) { useScreen = false; }
  12452. if (!useScreen && this._currentRenderTarget) {
  12453. return this._currentRenderTarget.height;
  12454. }
  12455. return this._gl.drawingBufferHeight;
  12456. };
  12457. /**
  12458. * Gets the HTML canvas attached with the current webGL context
  12459. * @returns a HTML canvas
  12460. */
  12461. Engine.prototype.getRenderingCanvas = function () {
  12462. return this._renderingCanvas;
  12463. };
  12464. /**
  12465. * Gets the client rect of the HTML canvas attached with the current webGL context
  12466. * @returns a client rectanglee
  12467. */
  12468. Engine.prototype.getRenderingCanvasClientRect = function () {
  12469. if (!this._renderingCanvas) {
  12470. return null;
  12471. }
  12472. return this._renderingCanvas.getBoundingClientRect();
  12473. };
  12474. /**
  12475. * Defines the hardware scaling level.
  12476. * By default the hardware scaling level is computed from the window device ratio.
  12477. * 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.
  12478. * @param level defines the level to use
  12479. */
  12480. Engine.prototype.setHardwareScalingLevel = function (level) {
  12481. this._hardwareScalingLevel = level;
  12482. this.resize();
  12483. };
  12484. /**
  12485. * Gets the current hardware scaling level.
  12486. * By default the hardware scaling level is computed from the window device ratio.
  12487. * 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.
  12488. * @returns a number indicating the current hardware scaling level
  12489. */
  12490. Engine.prototype.getHardwareScalingLevel = function () {
  12491. return this._hardwareScalingLevel;
  12492. };
  12493. /**
  12494. * Gets the list of loaded textures
  12495. * @returns an array containing all loaded textures
  12496. */
  12497. Engine.prototype.getLoadedTexturesCache = function () {
  12498. return this._internalTexturesCache;
  12499. };
  12500. /**
  12501. * Gets the object containing all engine capabilities
  12502. * @returns the EngineCapabilities object
  12503. */
  12504. Engine.prototype.getCaps = function () {
  12505. return this._caps;
  12506. };
  12507. Object.defineProperty(Engine.prototype, "drawCalls", {
  12508. /** @hidden */
  12509. get: function () {
  12510. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12511. return 0;
  12512. },
  12513. enumerable: true,
  12514. configurable: true
  12515. });
  12516. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12517. /** @hidden */
  12518. get: function () {
  12519. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12520. return null;
  12521. },
  12522. enumerable: true,
  12523. configurable: true
  12524. });
  12525. /**
  12526. * Gets the current depth function
  12527. * @returns a number defining the depth function
  12528. */
  12529. Engine.prototype.getDepthFunction = function () {
  12530. return this._depthCullingState.depthFunc;
  12531. };
  12532. /**
  12533. * Sets the current depth function
  12534. * @param depthFunc defines the function to use
  12535. */
  12536. Engine.prototype.setDepthFunction = function (depthFunc) {
  12537. this._depthCullingState.depthFunc = depthFunc;
  12538. };
  12539. /**
  12540. * Sets the current depth function to GREATER
  12541. */
  12542. Engine.prototype.setDepthFunctionToGreater = function () {
  12543. this._depthCullingState.depthFunc = this._gl.GREATER;
  12544. };
  12545. /**
  12546. * Sets the current depth function to GEQUAL
  12547. */
  12548. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12549. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12550. };
  12551. /**
  12552. * Sets the current depth function to LESS
  12553. */
  12554. Engine.prototype.setDepthFunctionToLess = function () {
  12555. this._depthCullingState.depthFunc = this._gl.LESS;
  12556. };
  12557. /**
  12558. * Sets the current depth function to LEQUAL
  12559. */
  12560. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12561. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12562. };
  12563. /**
  12564. * Gets a boolean indicating if stencil buffer is enabled
  12565. * @returns the current stencil buffer state
  12566. */
  12567. Engine.prototype.getStencilBuffer = function () {
  12568. return this._stencilState.stencilTest;
  12569. };
  12570. /**
  12571. * Enable or disable the stencil buffer
  12572. * @param enable defines if the stencil buffer must be enabled or disabled
  12573. */
  12574. Engine.prototype.setStencilBuffer = function (enable) {
  12575. this._stencilState.stencilTest = enable;
  12576. };
  12577. /**
  12578. * Gets the current stencil mask
  12579. * @returns a number defining the new stencil mask to use
  12580. */
  12581. Engine.prototype.getStencilMask = function () {
  12582. return this._stencilState.stencilMask;
  12583. };
  12584. /**
  12585. * Sets the current stencil mask
  12586. * @param mask defines the new stencil mask to use
  12587. */
  12588. Engine.prototype.setStencilMask = function (mask) {
  12589. this._stencilState.stencilMask = mask;
  12590. };
  12591. /**
  12592. * Gets the current stencil function
  12593. * @returns a number defining the stencil function to use
  12594. */
  12595. Engine.prototype.getStencilFunction = function () {
  12596. return this._stencilState.stencilFunc;
  12597. };
  12598. /**
  12599. * Gets the current stencil reference value
  12600. * @returns a number defining the stencil reference value to use
  12601. */
  12602. Engine.prototype.getStencilFunctionReference = function () {
  12603. return this._stencilState.stencilFuncRef;
  12604. };
  12605. /**
  12606. * Gets the current stencil mask
  12607. * @returns a number defining the stencil mask to use
  12608. */
  12609. Engine.prototype.getStencilFunctionMask = function () {
  12610. return this._stencilState.stencilFuncMask;
  12611. };
  12612. /**
  12613. * Sets the current stencil function
  12614. * @param stencilFunc defines the new stencil function to use
  12615. */
  12616. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12617. this._stencilState.stencilFunc = stencilFunc;
  12618. };
  12619. /**
  12620. * Sets the current stencil reference
  12621. * @param reference defines the new stencil reference to use
  12622. */
  12623. Engine.prototype.setStencilFunctionReference = function (reference) {
  12624. this._stencilState.stencilFuncRef = reference;
  12625. };
  12626. /**
  12627. * Sets the current stencil mask
  12628. * @param mask defines the new stencil mask to use
  12629. */
  12630. Engine.prototype.setStencilFunctionMask = function (mask) {
  12631. this._stencilState.stencilFuncMask = mask;
  12632. };
  12633. /**
  12634. * Gets the current stencil operation when stencil fails
  12635. * @returns a number defining stencil operation to use when stencil fails
  12636. */
  12637. Engine.prototype.getStencilOperationFail = function () {
  12638. return this._stencilState.stencilOpStencilFail;
  12639. };
  12640. /**
  12641. * Gets the current stencil operation when depth fails
  12642. * @returns a number defining stencil operation to use when depth fails
  12643. */
  12644. Engine.prototype.getStencilOperationDepthFail = function () {
  12645. return this._stencilState.stencilOpDepthFail;
  12646. };
  12647. /**
  12648. * Gets the current stencil operation when stencil passes
  12649. * @returns a number defining stencil operation to use when stencil passes
  12650. */
  12651. Engine.prototype.getStencilOperationPass = function () {
  12652. return this._stencilState.stencilOpStencilDepthPass;
  12653. };
  12654. /**
  12655. * Sets the stencil operation to use when stencil fails
  12656. * @param operation defines the stencil operation to use when stencil fails
  12657. */
  12658. Engine.prototype.setStencilOperationFail = function (operation) {
  12659. this._stencilState.stencilOpStencilFail = operation;
  12660. };
  12661. /**
  12662. * Sets the stencil operation to use when depth fails
  12663. * @param operation defines the stencil operation to use when depth fails
  12664. */
  12665. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12666. this._stencilState.stencilOpDepthFail = operation;
  12667. };
  12668. /**
  12669. * Sets the stencil operation to use when stencil passes
  12670. * @param operation defines the stencil operation to use when stencil passes
  12671. */
  12672. Engine.prototype.setStencilOperationPass = function (operation) {
  12673. this._stencilState.stencilOpStencilDepthPass = operation;
  12674. };
  12675. /**
  12676. * Sets a boolean indicating if the dithering state is enabled or disabled
  12677. * @param value defines the dithering state
  12678. */
  12679. Engine.prototype.setDitheringState = function (value) {
  12680. if (value) {
  12681. this._gl.enable(this._gl.DITHER);
  12682. }
  12683. else {
  12684. this._gl.disable(this._gl.DITHER);
  12685. }
  12686. };
  12687. /**
  12688. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12689. * @param value defines the rasterizer state
  12690. */
  12691. Engine.prototype.setRasterizerState = function (value) {
  12692. if (value) {
  12693. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12694. }
  12695. else {
  12696. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12697. }
  12698. };
  12699. /**
  12700. * stop executing a render loop function and remove it from the execution array
  12701. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12702. */
  12703. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12704. if (!renderFunction) {
  12705. this._activeRenderLoops = [];
  12706. return;
  12707. }
  12708. var index = this._activeRenderLoops.indexOf(renderFunction);
  12709. if (index >= 0) {
  12710. this._activeRenderLoops.splice(index, 1);
  12711. }
  12712. };
  12713. /** @hidden */
  12714. Engine.prototype._renderLoop = function () {
  12715. if (!this._contextWasLost) {
  12716. var shouldRender = true;
  12717. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12718. shouldRender = false;
  12719. }
  12720. if (shouldRender) {
  12721. // Start new frame
  12722. this.beginFrame();
  12723. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12724. var renderFunction = this._activeRenderLoops[index];
  12725. renderFunction();
  12726. }
  12727. // Present
  12728. this.endFrame();
  12729. }
  12730. }
  12731. if (this._activeRenderLoops.length > 0) {
  12732. // Register new frame
  12733. var requester = null;
  12734. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12735. requester = this._vrDisplay;
  12736. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12737. }
  12738. else {
  12739. this._renderingQueueLaunched = false;
  12740. }
  12741. };
  12742. /**
  12743. * Register and execute a render loop. The engine can have more than one render function
  12744. * @param renderFunction defines the function to continuously execute
  12745. */
  12746. Engine.prototype.runRenderLoop = function (renderFunction) {
  12747. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12748. return;
  12749. }
  12750. this._activeRenderLoops.push(renderFunction);
  12751. if (!this._renderingQueueLaunched) {
  12752. this._renderingQueueLaunched = true;
  12753. this._bindedRenderFunction = this._renderLoop.bind(this);
  12754. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12755. }
  12756. };
  12757. /**
  12758. * Toggle full screen mode
  12759. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12760. * @param options defines an option object to be sent to the requestFullscreen function
  12761. */
  12762. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12763. if (this.isFullscreen) {
  12764. BABYLON.Tools.ExitFullscreen();
  12765. }
  12766. else {
  12767. this._pointerLockRequested = requestPointerLock;
  12768. if (this._renderingCanvas) {
  12769. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12770. }
  12771. }
  12772. };
  12773. /**
  12774. * Clear the current render buffer or the current render target (if any is set up)
  12775. * @param color defines the color to use
  12776. * @param backBuffer defines if the back buffer must be cleared
  12777. * @param depth defines if the depth buffer must be cleared
  12778. * @param stencil defines if the stencil buffer must be cleared
  12779. */
  12780. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12781. if (stencil === void 0) { stencil = false; }
  12782. this.applyStates();
  12783. var mode = 0;
  12784. if (backBuffer && color) {
  12785. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12786. mode |= this._gl.COLOR_BUFFER_BIT;
  12787. }
  12788. if (depth) {
  12789. this._gl.clearDepth(1.0);
  12790. mode |= this._gl.DEPTH_BUFFER_BIT;
  12791. }
  12792. if (stencil) {
  12793. this._gl.clearStencil(0);
  12794. mode |= this._gl.STENCIL_BUFFER_BIT;
  12795. }
  12796. this._gl.clear(mode);
  12797. };
  12798. /**
  12799. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12800. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12801. * @param y defines the y-coordinate of the corner of the clear rectangle
  12802. * @param width defines the width of the clear rectangle
  12803. * @param height defines the height of the clear rectangle
  12804. * @param clearColor defines the clear color
  12805. */
  12806. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12807. var gl = this._gl;
  12808. // Save state
  12809. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12810. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12811. // Change state
  12812. gl.enable(gl.SCISSOR_TEST);
  12813. gl.scissor(x, y, width, height);
  12814. // Clear
  12815. this.clear(clearColor, true, true, true);
  12816. // Restore state
  12817. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12818. if (curScissor === true) {
  12819. gl.enable(gl.SCISSOR_TEST);
  12820. }
  12821. else {
  12822. gl.disable(gl.SCISSOR_TEST);
  12823. }
  12824. };
  12825. /**
  12826. * Set the WebGL's viewport
  12827. * @param viewport defines the viewport element to be used
  12828. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12829. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12830. */
  12831. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12832. var width = requiredWidth || this.getRenderWidth();
  12833. var height = requiredHeight || this.getRenderHeight();
  12834. var x = viewport.x || 0;
  12835. var y = viewport.y || 0;
  12836. this._cachedViewport = viewport;
  12837. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12838. };
  12839. /**
  12840. * Directly set the WebGL Viewport
  12841. * @param x defines the x coordinate of the viewport (in screen space)
  12842. * @param y defines the y coordinate of the viewport (in screen space)
  12843. * @param width defines the width of the viewport (in screen space)
  12844. * @param height defines the height of the viewport (in screen space)
  12845. * @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
  12846. */
  12847. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12848. var currentViewport = this._cachedViewport;
  12849. this._cachedViewport = null;
  12850. this._gl.viewport(x, y, width, height);
  12851. return currentViewport;
  12852. };
  12853. /**
  12854. * Begin a new frame
  12855. */
  12856. Engine.prototype.beginFrame = function () {
  12857. this.onBeginFrameObservable.notifyObservers(this);
  12858. this._measureFps();
  12859. };
  12860. /**
  12861. * Enf the current frame
  12862. */
  12863. Engine.prototype.endFrame = function () {
  12864. // Force a flush in case we are using a bad OS.
  12865. if (this._badOS) {
  12866. this.flushFramebuffer();
  12867. }
  12868. // Submit frame to the vr device, if enabled
  12869. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12870. // TODO: We should only submit the frame if we read frameData successfully.
  12871. this._vrDisplay.submitFrame();
  12872. }
  12873. this.onEndFrameObservable.notifyObservers(this);
  12874. };
  12875. /**
  12876. * Resize the view according to the canvas' size
  12877. */
  12878. Engine.prototype.resize = function () {
  12879. // We're not resizing the size of the canvas while in VR mode & presenting
  12880. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12881. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12882. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12883. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12884. }
  12885. };
  12886. /**
  12887. * Force a specific size of the canvas
  12888. * @param width defines the new canvas' width
  12889. * @param height defines the new canvas' height
  12890. */
  12891. Engine.prototype.setSize = function (width, height) {
  12892. if (!this._renderingCanvas) {
  12893. return;
  12894. }
  12895. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12896. return;
  12897. }
  12898. this._renderingCanvas.width = width;
  12899. this._renderingCanvas.height = height;
  12900. for (var index = 0; index < this.scenes.length; index++) {
  12901. var scene = this.scenes[index];
  12902. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12903. var cam = scene.cameras[camIndex];
  12904. cam._currentRenderId = 0;
  12905. }
  12906. }
  12907. if (this.onResizeObservable.hasObservers) {
  12908. this.onResizeObservable.notifyObservers(this);
  12909. }
  12910. };
  12911. // WebVR functions
  12912. /**
  12913. * Gets a boolean indicating if a webVR device was detected
  12914. * @returns true if a webVR device was detected
  12915. */
  12916. Engine.prototype.isVRDevicePresent = function () {
  12917. return !!this._vrDisplay;
  12918. };
  12919. /**
  12920. * Gets the current webVR device
  12921. * @returns the current webVR device (or null)
  12922. */
  12923. Engine.prototype.getVRDevice = function () {
  12924. return this._vrDisplay;
  12925. };
  12926. /**
  12927. * Initializes a webVR display and starts listening to display change events
  12928. * The onVRDisplayChangedObservable will be notified upon these changes
  12929. * @returns The onVRDisplayChangedObservable
  12930. */
  12931. Engine.prototype.initWebVR = function () {
  12932. this.initWebVRAsync();
  12933. return this.onVRDisplayChangedObservable;
  12934. };
  12935. /**
  12936. * Initializes a webVR display and starts listening to display change events
  12937. * The onVRDisplayChangedObservable will be notified upon these changes
  12938. * @returns A promise containing a VRDisplay and if vr is supported
  12939. */
  12940. Engine.prototype.initWebVRAsync = function () {
  12941. var _this = this;
  12942. var notifyObservers = function () {
  12943. var eventArgs = {
  12944. vrDisplay: _this._vrDisplay,
  12945. vrSupported: _this._vrSupported
  12946. };
  12947. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12948. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12949. };
  12950. if (!this._onVrDisplayConnect) {
  12951. this._onVrDisplayConnect = function (event) {
  12952. _this._vrDisplay = event.display;
  12953. notifyObservers();
  12954. };
  12955. this._onVrDisplayDisconnect = function () {
  12956. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12957. _this._vrDisplay = undefined;
  12958. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12959. notifyObservers();
  12960. };
  12961. this._onVrDisplayPresentChange = function () {
  12962. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12963. };
  12964. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12965. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12966. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12967. }
  12968. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12969. this._webVRInitPromise.then(notifyObservers);
  12970. return this._webVRInitPromise;
  12971. };
  12972. /**
  12973. * Call this function to switch to webVR mode
  12974. * Will do nothing if webVR is not supported or if there is no webVR device
  12975. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12976. */
  12977. Engine.prototype.enableVR = function () {
  12978. var _this = this;
  12979. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12980. var onResolved = function () {
  12981. _this.onVRRequestPresentComplete.notifyObservers(true);
  12982. _this._onVRFullScreenTriggered();
  12983. };
  12984. var onRejected = function () {
  12985. _this.onVRRequestPresentComplete.notifyObservers(false);
  12986. };
  12987. this.onVRRequestPresentStart.notifyObservers(this);
  12988. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12989. }
  12990. };
  12991. /**
  12992. * Call this function to leave webVR mode
  12993. * Will do nothing if webVR is not supported or if there is no webVR device
  12994. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12995. */
  12996. Engine.prototype.disableVR = function () {
  12997. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12998. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12999. }
  13000. };
  13001. Engine.prototype._getVRDisplaysAsync = function () {
  13002. var _this = this;
  13003. return new Promise(function (res, rej) {
  13004. if (navigator.getVRDisplays) {
  13005. navigator.getVRDisplays().then(function (devices) {
  13006. _this._vrSupported = true;
  13007. // note that devices may actually be an empty array. This is fine;
  13008. // we expect this._vrDisplay to be undefined in this case.
  13009. _this._vrDisplay = devices[0];
  13010. res({
  13011. vrDisplay: _this._vrDisplay,
  13012. vrSupported: _this._vrSupported
  13013. });
  13014. });
  13015. }
  13016. else {
  13017. _this._vrDisplay = undefined;
  13018. _this._vrSupported = false;
  13019. res({
  13020. vrDisplay: _this._vrDisplay,
  13021. vrSupported: _this._vrSupported
  13022. });
  13023. }
  13024. });
  13025. };
  13026. /**
  13027. * Binds the frame buffer to the specified texture.
  13028. * @param texture The texture to render to or null for the default canvas
  13029. * @param faceIndex The face of the texture to render to in case of cube texture
  13030. * @param requiredWidth The width of the target to render to
  13031. * @param requiredHeight The height of the target to render to
  13032. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13033. * @param depthStencilTexture The depth stencil texture to use to render
  13034. * @param lodLevel defines le lod level to bind to the frame buffer
  13035. */
  13036. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13037. if (lodLevel === void 0) { lodLevel = 0; }
  13038. if (this._currentRenderTarget) {
  13039. this.unBindFramebuffer(this._currentRenderTarget);
  13040. }
  13041. this._currentRenderTarget = texture;
  13042. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13043. var gl = this._gl;
  13044. if (texture.isCube) {
  13045. if (faceIndex === undefined) {
  13046. faceIndex = 0;
  13047. }
  13048. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13049. if (depthStencilTexture) {
  13050. if (depthStencilTexture._generateStencilBuffer) {
  13051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13052. }
  13053. else {
  13054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13055. }
  13056. }
  13057. }
  13058. if (this._cachedViewport && !forceFullscreenViewport) {
  13059. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13060. }
  13061. else {
  13062. if (!requiredWidth) {
  13063. requiredWidth = texture.width;
  13064. if (lodLevel) {
  13065. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13066. }
  13067. }
  13068. if (!requiredHeight) {
  13069. requiredHeight = texture.height;
  13070. if (lodLevel) {
  13071. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13072. }
  13073. }
  13074. gl.viewport(0, 0, requiredWidth, requiredHeight);
  13075. }
  13076. this.wipeCaches();
  13077. };
  13078. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13079. if (this._currentFramebuffer !== framebuffer) {
  13080. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13081. this._currentFramebuffer = framebuffer;
  13082. }
  13083. };
  13084. /**
  13085. * Unbind the current render target texture from the webGL context
  13086. * @param texture defines the render target texture to unbind
  13087. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13088. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13089. */
  13090. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13091. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13092. this._currentRenderTarget = null;
  13093. // If MSAA, we need to bitblt back to main texture
  13094. var gl = this._gl;
  13095. if (texture._MSAAFramebuffer) {
  13096. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13097. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13098. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13099. }
  13100. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13101. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13102. gl.generateMipmap(gl.TEXTURE_2D);
  13103. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13104. }
  13105. if (onBeforeUnbind) {
  13106. if (texture._MSAAFramebuffer) {
  13107. // Bind the correct framebuffer
  13108. this.bindUnboundFramebuffer(texture._framebuffer);
  13109. }
  13110. onBeforeUnbind();
  13111. }
  13112. this.bindUnboundFramebuffer(null);
  13113. };
  13114. /**
  13115. * Unbind a list of render target textures from the webGL context
  13116. * This is used only when drawBuffer extension or webGL2 are active
  13117. * @param textures defines the render target textures to unbind
  13118. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13119. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13120. */
  13121. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13122. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13123. this._currentRenderTarget = null;
  13124. // If MSAA, we need to bitblt back to main texture
  13125. var gl = this._gl;
  13126. if (textures[0]._MSAAFramebuffer) {
  13127. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13128. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13129. var attachments = textures[0]._attachments;
  13130. if (!attachments) {
  13131. attachments = new Array(textures.length);
  13132. textures[0]._attachments = attachments;
  13133. }
  13134. for (var i = 0; i < textures.length; i++) {
  13135. var texture = textures[i];
  13136. for (var j = 0; j < attachments.length; j++) {
  13137. attachments[j] = gl.NONE;
  13138. }
  13139. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13140. gl.readBuffer(attachments[i]);
  13141. gl.drawBuffers(attachments);
  13142. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13143. }
  13144. for (var i = 0; i < attachments.length; i++) {
  13145. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13146. }
  13147. gl.drawBuffers(attachments);
  13148. }
  13149. for (var i = 0; i < textures.length; i++) {
  13150. var texture = textures[i];
  13151. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13152. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13153. gl.generateMipmap(gl.TEXTURE_2D);
  13154. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13155. }
  13156. }
  13157. if (onBeforeUnbind) {
  13158. if (textures[0]._MSAAFramebuffer) {
  13159. // Bind the correct framebuffer
  13160. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13161. }
  13162. onBeforeUnbind();
  13163. }
  13164. this.bindUnboundFramebuffer(null);
  13165. };
  13166. /**
  13167. * Force the mipmap generation for the given render target texture
  13168. * @param texture defines the render target texture to use
  13169. */
  13170. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13171. if (texture.generateMipMaps) {
  13172. var gl = this._gl;
  13173. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13174. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13175. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13176. }
  13177. };
  13178. /**
  13179. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13180. */
  13181. Engine.prototype.flushFramebuffer = function () {
  13182. this._gl.flush();
  13183. };
  13184. /**
  13185. * Unbind the current render target and bind the default framebuffer
  13186. */
  13187. Engine.prototype.restoreDefaultFramebuffer = function () {
  13188. if (this._currentRenderTarget) {
  13189. this.unBindFramebuffer(this._currentRenderTarget);
  13190. }
  13191. else {
  13192. this.bindUnboundFramebuffer(null);
  13193. }
  13194. if (this._cachedViewport) {
  13195. this.setViewport(this._cachedViewport);
  13196. }
  13197. this.wipeCaches();
  13198. };
  13199. // UBOs
  13200. /**
  13201. * Create an uniform buffer
  13202. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13203. * @param elements defines the content of the uniform buffer
  13204. * @returns the webGL uniform buffer
  13205. */
  13206. Engine.prototype.createUniformBuffer = function (elements) {
  13207. var ubo = this._gl.createBuffer();
  13208. if (!ubo) {
  13209. throw new Error("Unable to create uniform buffer");
  13210. }
  13211. this.bindUniformBuffer(ubo);
  13212. if (elements instanceof Float32Array) {
  13213. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13214. }
  13215. else {
  13216. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13217. }
  13218. this.bindUniformBuffer(null);
  13219. ubo.references = 1;
  13220. return ubo;
  13221. };
  13222. /**
  13223. * Create a dynamic uniform buffer
  13224. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13225. * @param elements defines the content of the uniform buffer
  13226. * @returns the webGL uniform buffer
  13227. */
  13228. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13229. var ubo = this._gl.createBuffer();
  13230. if (!ubo) {
  13231. throw new Error("Unable to create dynamic uniform buffer");
  13232. }
  13233. this.bindUniformBuffer(ubo);
  13234. if (elements instanceof Float32Array) {
  13235. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13236. }
  13237. else {
  13238. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13239. }
  13240. this.bindUniformBuffer(null);
  13241. ubo.references = 1;
  13242. return ubo;
  13243. };
  13244. /**
  13245. * Update an existing uniform buffer
  13246. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13247. * @param uniformBuffer defines the target uniform buffer
  13248. * @param elements defines the content to update
  13249. * @param offset defines the offset in the uniform buffer where update should start
  13250. * @param count defines the size of the data to update
  13251. */
  13252. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13253. this.bindUniformBuffer(uniformBuffer);
  13254. if (offset === undefined) {
  13255. offset = 0;
  13256. }
  13257. if (count === undefined) {
  13258. if (elements instanceof Float32Array) {
  13259. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13260. }
  13261. else {
  13262. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13263. }
  13264. }
  13265. else {
  13266. if (elements instanceof Float32Array) {
  13267. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13268. }
  13269. else {
  13270. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13271. }
  13272. }
  13273. this.bindUniformBuffer(null);
  13274. };
  13275. // VBOs
  13276. Engine.prototype._resetVertexBufferBinding = function () {
  13277. this.bindArrayBuffer(null);
  13278. this._cachedVertexBuffers = null;
  13279. };
  13280. /**
  13281. * Creates a vertex buffer
  13282. * @param data the data for the vertex buffer
  13283. * @returns the new WebGL static buffer
  13284. */
  13285. Engine.prototype.createVertexBuffer = function (data) {
  13286. var vbo = this._gl.createBuffer();
  13287. if (!vbo) {
  13288. throw new Error("Unable to create vertex buffer");
  13289. }
  13290. this.bindArrayBuffer(vbo);
  13291. if (data instanceof Array) {
  13292. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13293. }
  13294. else {
  13295. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13296. }
  13297. this._resetVertexBufferBinding();
  13298. vbo.references = 1;
  13299. return vbo;
  13300. };
  13301. /**
  13302. * Creates a dynamic vertex buffer
  13303. * @param data the data for the dynamic vertex buffer
  13304. * @returns the new WebGL dynamic buffer
  13305. */
  13306. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13307. var vbo = this._gl.createBuffer();
  13308. if (!vbo) {
  13309. throw new Error("Unable to create dynamic vertex buffer");
  13310. }
  13311. this.bindArrayBuffer(vbo);
  13312. if (data instanceof Array) {
  13313. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13314. }
  13315. else {
  13316. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13317. }
  13318. this._resetVertexBufferBinding();
  13319. vbo.references = 1;
  13320. return vbo;
  13321. };
  13322. /**
  13323. * Update a dynamic index buffer
  13324. * @param indexBuffer defines the target index buffer
  13325. * @param indices defines the data to update
  13326. * @param offset defines the offset in the target index buffer where update should start
  13327. */
  13328. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13329. if (offset === void 0) { offset = 0; }
  13330. // Force cache update
  13331. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13332. this.bindIndexBuffer(indexBuffer);
  13333. var arrayBuffer;
  13334. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13335. arrayBuffer = indices;
  13336. }
  13337. else {
  13338. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13339. }
  13340. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13341. this._resetIndexBufferBinding();
  13342. };
  13343. /**
  13344. * Updates a dynamic vertex buffer.
  13345. * @param vertexBuffer the vertex buffer to update
  13346. * @param data the data used to update the vertex buffer
  13347. * @param byteOffset the byte offset of the data
  13348. * @param byteLength the byte length of the data
  13349. */
  13350. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13351. this.bindArrayBuffer(vertexBuffer);
  13352. if (byteOffset === undefined) {
  13353. byteOffset = 0;
  13354. }
  13355. if (byteLength === undefined) {
  13356. if (data instanceof Array) {
  13357. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13358. }
  13359. else {
  13360. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13361. }
  13362. }
  13363. else {
  13364. if (data instanceof Array) {
  13365. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13366. }
  13367. else {
  13368. if (data instanceof ArrayBuffer) {
  13369. data = new Uint8Array(data, byteOffset, byteLength);
  13370. }
  13371. else {
  13372. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13373. }
  13374. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13375. }
  13376. }
  13377. this._resetVertexBufferBinding();
  13378. };
  13379. Engine.prototype._resetIndexBufferBinding = function () {
  13380. this.bindIndexBuffer(null);
  13381. this._cachedIndexBuffer = null;
  13382. };
  13383. /**
  13384. * Creates a new index buffer
  13385. * @param indices defines the content of the index buffer
  13386. * @param updatable defines if the index buffer must be updatable
  13387. * @returns a new webGL buffer
  13388. */
  13389. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13390. var vbo = this._gl.createBuffer();
  13391. if (!vbo) {
  13392. throw new Error("Unable to create index buffer");
  13393. }
  13394. this.bindIndexBuffer(vbo);
  13395. // Check for 32 bits indices
  13396. var arrayBuffer;
  13397. var need32Bits = false;
  13398. if (indices instanceof Uint16Array) {
  13399. arrayBuffer = indices;
  13400. }
  13401. else {
  13402. //check 32 bit support
  13403. if (this._caps.uintIndices) {
  13404. if (indices instanceof Uint32Array) {
  13405. arrayBuffer = indices;
  13406. need32Bits = true;
  13407. }
  13408. else {
  13409. //number[] or Int32Array, check if 32 bit is necessary
  13410. for (var index = 0; index < indices.length; index++) {
  13411. if (indices[index] > 65535) {
  13412. need32Bits = true;
  13413. break;
  13414. }
  13415. }
  13416. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13417. }
  13418. }
  13419. else {
  13420. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13421. arrayBuffer = new Uint16Array(indices);
  13422. }
  13423. }
  13424. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13425. this._resetIndexBufferBinding();
  13426. vbo.references = 1;
  13427. vbo.is32Bits = need32Bits;
  13428. return vbo;
  13429. };
  13430. /**
  13431. * Bind a webGL buffer to the webGL context
  13432. * @param buffer defines the buffer to bind
  13433. */
  13434. Engine.prototype.bindArrayBuffer = function (buffer) {
  13435. if (!this._vaoRecordInProgress) {
  13436. this._unbindVertexArrayObject();
  13437. }
  13438. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13439. };
  13440. /**
  13441. * Bind an uniform buffer to the current webGL context
  13442. * @param buffer defines the buffer to bind
  13443. */
  13444. Engine.prototype.bindUniformBuffer = function (buffer) {
  13445. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13446. };
  13447. /**
  13448. * Bind a buffer to the current webGL context at a given location
  13449. * @param buffer defines the buffer to bind
  13450. * @param location defines the index where to bind the buffer
  13451. */
  13452. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13453. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13454. };
  13455. /**
  13456. * Bind a specific block at a given index in a specific shader program
  13457. * @param shaderProgram defines the shader program
  13458. * @param blockName defines the block name
  13459. * @param index defines the index where to bind the block
  13460. */
  13461. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13462. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13463. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13464. };
  13465. ;
  13466. Engine.prototype.bindIndexBuffer = function (buffer) {
  13467. if (!this._vaoRecordInProgress) {
  13468. this._unbindVertexArrayObject();
  13469. }
  13470. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13471. };
  13472. Engine.prototype.bindBuffer = function (buffer, target) {
  13473. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13474. this._gl.bindBuffer(target, buffer);
  13475. this._currentBoundBuffer[target] = buffer;
  13476. }
  13477. };
  13478. /**
  13479. * update the bound buffer with the given data
  13480. * @param data defines the data to update
  13481. */
  13482. Engine.prototype.updateArrayBuffer = function (data) {
  13483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13484. };
  13485. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13486. var pointer = this._currentBufferPointers[indx];
  13487. var changed = false;
  13488. if (!pointer.active) {
  13489. changed = true;
  13490. pointer.active = true;
  13491. pointer.index = indx;
  13492. pointer.size = size;
  13493. pointer.type = type;
  13494. pointer.normalized = normalized;
  13495. pointer.stride = stride;
  13496. pointer.offset = offset;
  13497. pointer.buffer = buffer;
  13498. }
  13499. else {
  13500. if (pointer.buffer !== buffer) {
  13501. pointer.buffer = buffer;
  13502. changed = true;
  13503. }
  13504. if (pointer.size !== size) {
  13505. pointer.size = size;
  13506. changed = true;
  13507. }
  13508. if (pointer.type !== type) {
  13509. pointer.type = type;
  13510. changed = true;
  13511. }
  13512. if (pointer.normalized !== normalized) {
  13513. pointer.normalized = normalized;
  13514. changed = true;
  13515. }
  13516. if (pointer.stride !== stride) {
  13517. pointer.stride = stride;
  13518. changed = true;
  13519. }
  13520. if (pointer.offset !== offset) {
  13521. pointer.offset = offset;
  13522. changed = true;
  13523. }
  13524. }
  13525. if (changed || this._vaoRecordInProgress) {
  13526. this.bindArrayBuffer(buffer);
  13527. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13528. }
  13529. };
  13530. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13531. if (indexBuffer == null) {
  13532. return;
  13533. }
  13534. if (this._cachedIndexBuffer !== indexBuffer) {
  13535. this._cachedIndexBuffer = indexBuffer;
  13536. this.bindIndexBuffer(indexBuffer);
  13537. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13538. }
  13539. };
  13540. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13541. var attributes = effect.getAttributesNames();
  13542. if (!this._vaoRecordInProgress) {
  13543. this._unbindVertexArrayObject();
  13544. }
  13545. this.unbindAllAttributes();
  13546. for (var index = 0; index < attributes.length; index++) {
  13547. var order = effect.getAttributeLocation(index);
  13548. if (order >= 0) {
  13549. var vertexBuffer = vertexBuffers[attributes[index]];
  13550. if (!vertexBuffer) {
  13551. continue;
  13552. }
  13553. this._gl.enableVertexAttribArray(order);
  13554. if (!this._vaoRecordInProgress) {
  13555. this._vertexAttribArraysEnabled[order] = true;
  13556. }
  13557. var buffer = vertexBuffer.getBuffer();
  13558. if (buffer) {
  13559. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13560. if (vertexBuffer.getIsInstanced()) {
  13561. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13562. if (!this._vaoRecordInProgress) {
  13563. this._currentInstanceLocations.push(order);
  13564. this._currentInstanceBuffers.push(buffer);
  13565. }
  13566. }
  13567. }
  13568. }
  13569. }
  13570. };
  13571. /**
  13572. * Records a vertex array object
  13573. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13574. * @param vertexBuffers defines the list of vertex buffers to store
  13575. * @param indexBuffer defines the index buffer to store
  13576. * @param effect defines the effect to store
  13577. * @returns the new vertex array object
  13578. */
  13579. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13580. var vao = this._gl.createVertexArray();
  13581. this._vaoRecordInProgress = true;
  13582. this._gl.bindVertexArray(vao);
  13583. this._mustWipeVertexAttributes = true;
  13584. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13585. this.bindIndexBuffer(indexBuffer);
  13586. this._vaoRecordInProgress = false;
  13587. this._gl.bindVertexArray(null);
  13588. return vao;
  13589. };
  13590. /**
  13591. * Bind a specific vertex array object
  13592. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13593. * @param vertexArrayObject defines the vertex array object to bind
  13594. * @param indexBuffer defines the index buffer to bind
  13595. */
  13596. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13597. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13598. this._cachedVertexArrayObject = vertexArrayObject;
  13599. this._gl.bindVertexArray(vertexArrayObject);
  13600. this._cachedVertexBuffers = null;
  13601. this._cachedIndexBuffer = null;
  13602. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13603. this._mustWipeVertexAttributes = true;
  13604. }
  13605. };
  13606. /**
  13607. * Bind webGl buffers directly to the webGL context
  13608. * @param vertexBuffer defines the vertex buffer to bind
  13609. * @param indexBuffer defines the index buffer to bind
  13610. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13611. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13612. * @param effect defines the effect associated with the vertex buffer
  13613. */
  13614. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13615. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13616. this._cachedVertexBuffers = vertexBuffer;
  13617. this._cachedEffectForVertexBuffers = effect;
  13618. var attributesCount = effect.getAttributesCount();
  13619. this._unbindVertexArrayObject();
  13620. this.unbindAllAttributes();
  13621. var offset = 0;
  13622. for (var index = 0; index < attributesCount; index++) {
  13623. if (index < vertexDeclaration.length) {
  13624. var order = effect.getAttributeLocation(index);
  13625. if (order >= 0) {
  13626. this._gl.enableVertexAttribArray(order);
  13627. this._vertexAttribArraysEnabled[order] = true;
  13628. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13629. }
  13630. offset += vertexDeclaration[index] * 4;
  13631. }
  13632. }
  13633. }
  13634. this._bindIndexBufferWithCache(indexBuffer);
  13635. };
  13636. Engine.prototype._unbindVertexArrayObject = function () {
  13637. if (!this._cachedVertexArrayObject) {
  13638. return;
  13639. }
  13640. this._cachedVertexArrayObject = null;
  13641. this._gl.bindVertexArray(null);
  13642. };
  13643. /**
  13644. * Bind a list of vertex buffers to the webGL context
  13645. * @param vertexBuffers defines the list of vertex buffers to bind
  13646. * @param indexBuffer defines the index buffer to bind
  13647. * @param effect defines the effect associated with the vertex buffers
  13648. */
  13649. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13650. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13651. this._cachedVertexBuffers = vertexBuffers;
  13652. this._cachedEffectForVertexBuffers = effect;
  13653. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13654. }
  13655. this._bindIndexBufferWithCache(indexBuffer);
  13656. };
  13657. /**
  13658. * Unbind all instance attributes
  13659. */
  13660. Engine.prototype.unbindInstanceAttributes = function () {
  13661. var boundBuffer;
  13662. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13663. var instancesBuffer = this._currentInstanceBuffers[i];
  13664. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13665. boundBuffer = instancesBuffer;
  13666. this.bindArrayBuffer(instancesBuffer);
  13667. }
  13668. var offsetLocation = this._currentInstanceLocations[i];
  13669. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13670. }
  13671. this._currentInstanceBuffers.length = 0;
  13672. this._currentInstanceLocations.length = 0;
  13673. };
  13674. /**
  13675. * Release and free the memory of a vertex array object
  13676. * @param vao defines the vertex array object to delete
  13677. */
  13678. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13679. this._gl.deleteVertexArray(vao);
  13680. };
  13681. /** @hidden */
  13682. Engine.prototype._releaseBuffer = function (buffer) {
  13683. buffer.references--;
  13684. if (buffer.references === 0) {
  13685. this._gl.deleteBuffer(buffer);
  13686. return true;
  13687. }
  13688. return false;
  13689. };
  13690. /**
  13691. * Creates a webGL buffer to use with instanciation
  13692. * @param capacity defines the size of the buffer
  13693. * @returns the webGL buffer
  13694. */
  13695. Engine.prototype.createInstancesBuffer = function (capacity) {
  13696. var buffer = this._gl.createBuffer();
  13697. if (!buffer) {
  13698. throw new Error("Unable to create instance buffer");
  13699. }
  13700. buffer.capacity = capacity;
  13701. this.bindArrayBuffer(buffer);
  13702. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13703. return buffer;
  13704. };
  13705. /**
  13706. * Delete a webGL buffer used with instanciation
  13707. * @param buffer defines the webGL buffer to delete
  13708. */
  13709. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13710. this._gl.deleteBuffer(buffer);
  13711. };
  13712. /**
  13713. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13714. * @param instancesBuffer defines the webGL buffer to update and bind
  13715. * @param data defines the data to store in the buffer
  13716. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13717. */
  13718. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13719. this.bindArrayBuffer(instancesBuffer);
  13720. if (data) {
  13721. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13722. }
  13723. if (offsetLocations[0].index !== undefined) {
  13724. var stride = 0;
  13725. for (var i = 0; i < offsetLocations.length; i++) {
  13726. var ai = offsetLocations[i];
  13727. stride += ai.attributeSize * 4;
  13728. }
  13729. for (var i = 0; i < offsetLocations.length; i++) {
  13730. var ai = offsetLocations[i];
  13731. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13732. this._gl.enableVertexAttribArray(ai.index);
  13733. this._vertexAttribArraysEnabled[ai.index] = true;
  13734. }
  13735. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13736. this._gl.vertexAttribDivisor(ai.index, 1);
  13737. this._currentInstanceLocations.push(ai.index);
  13738. this._currentInstanceBuffers.push(instancesBuffer);
  13739. }
  13740. }
  13741. else {
  13742. for (var index = 0; index < 4; index++) {
  13743. var offsetLocation = offsetLocations[index];
  13744. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13745. this._gl.enableVertexAttribArray(offsetLocation);
  13746. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13747. }
  13748. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13749. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13750. this._currentInstanceLocations.push(offsetLocation);
  13751. this._currentInstanceBuffers.push(instancesBuffer);
  13752. }
  13753. }
  13754. };
  13755. /**
  13756. * Apply all cached states (depth, culling, stencil and alpha)
  13757. */
  13758. Engine.prototype.applyStates = function () {
  13759. this._depthCullingState.apply(this._gl);
  13760. this._stencilState.apply(this._gl);
  13761. this._alphaState.apply(this._gl);
  13762. };
  13763. /**
  13764. * Send a draw order
  13765. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13766. * @param indexStart defines the starting index
  13767. * @param indexCount defines the number of index to draw
  13768. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13769. */
  13770. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13771. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13772. };
  13773. /**
  13774. * Draw a list of points
  13775. * @param verticesStart defines the index of first vertex to draw
  13776. * @param verticesCount defines the count of vertices to draw
  13777. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13778. */
  13779. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13780. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13781. };
  13782. /**
  13783. * Draw a list of unindexed primitives
  13784. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13785. * @param verticesStart defines the index of first vertex to draw
  13786. * @param verticesCount defines the count of vertices to draw
  13787. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13788. */
  13789. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13790. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13791. };
  13792. /**
  13793. * Draw a list of indexed primitives
  13794. * @param fillMode defines the primitive to use
  13795. * @param indexStart defines the starting index
  13796. * @param indexCount defines the number of index to draw
  13797. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13798. */
  13799. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13800. // Apply states
  13801. this.applyStates();
  13802. this._drawCalls.addCount(1, false);
  13803. // Render
  13804. var drawMode = this._drawMode(fillMode);
  13805. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13806. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13807. if (instancesCount) {
  13808. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13809. }
  13810. else {
  13811. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13812. }
  13813. };
  13814. /**
  13815. * Draw a list of unindexed primitives
  13816. * @param fillMode defines the primitive to use
  13817. * @param verticesStart defines the index of first vertex to draw
  13818. * @param verticesCount defines the count of vertices to draw
  13819. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13820. */
  13821. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13822. // Apply states
  13823. this.applyStates();
  13824. this._drawCalls.addCount(1, false);
  13825. var drawMode = this._drawMode(fillMode);
  13826. if (instancesCount) {
  13827. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13828. }
  13829. else {
  13830. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13831. }
  13832. };
  13833. Engine.prototype._drawMode = function (fillMode) {
  13834. switch (fillMode) {
  13835. // Triangle views
  13836. case BABYLON.Material.TriangleFillMode:
  13837. return this._gl.TRIANGLES;
  13838. case BABYLON.Material.PointFillMode:
  13839. return this._gl.POINTS;
  13840. case BABYLON.Material.WireFrameFillMode:
  13841. return this._gl.LINES;
  13842. // Draw modes
  13843. case BABYLON.Material.PointListDrawMode:
  13844. return this._gl.POINTS;
  13845. case BABYLON.Material.LineListDrawMode:
  13846. return this._gl.LINES;
  13847. case BABYLON.Material.LineLoopDrawMode:
  13848. return this._gl.LINE_LOOP;
  13849. case BABYLON.Material.LineStripDrawMode:
  13850. return this._gl.LINE_STRIP;
  13851. case BABYLON.Material.TriangleStripDrawMode:
  13852. return this._gl.TRIANGLE_STRIP;
  13853. case BABYLON.Material.TriangleFanDrawMode:
  13854. return this._gl.TRIANGLE_FAN;
  13855. default:
  13856. return this._gl.TRIANGLES;
  13857. }
  13858. };
  13859. // Shaders
  13860. /** @hidden */
  13861. Engine.prototype._releaseEffect = function (effect) {
  13862. if (this._compiledEffects[effect._key]) {
  13863. delete this._compiledEffects[effect._key];
  13864. this._deleteProgram(effect.getProgram());
  13865. }
  13866. };
  13867. /** @hidden */
  13868. Engine.prototype._deleteProgram = function (program) {
  13869. if (program) {
  13870. program.__SPECTOR_rebuildProgram = null;
  13871. if (program.transformFeedback) {
  13872. this.deleteTransformFeedback(program.transformFeedback);
  13873. program.transformFeedback = null;
  13874. }
  13875. this._gl.deleteProgram(program);
  13876. }
  13877. };
  13878. /**
  13879. * Create a new effect (used to store vertex/fragment shaders)
  13880. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13881. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13882. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13883. * @param samplers defines an array of string used to represent textures
  13884. * @param defines defines the string containing the defines to use to compile the shaders
  13885. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13886. * @param onCompiled defines a function to call when the effect creation is successful
  13887. * @param onError defines a function to call when the effect creation has failed
  13888. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13889. * @returns the new Effect
  13890. */
  13891. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13892. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13893. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13894. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13895. if (this._compiledEffects[name]) {
  13896. var compiledEffect = this._compiledEffects[name];
  13897. if (onCompiled && compiledEffect.isReady()) {
  13898. onCompiled(compiledEffect);
  13899. }
  13900. return compiledEffect;
  13901. }
  13902. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13903. effect._key = name;
  13904. this._compiledEffects[name] = effect;
  13905. return effect;
  13906. };
  13907. /**
  13908. * Create an effect to use with particle systems
  13909. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13910. * @param uniformsNames defines a list of attribute names
  13911. * @param samplers defines an array of string used to represent textures
  13912. * @param defines defines the string containing the defines to use to compile the shaders
  13913. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13914. * @param onCompiled defines a function to call when the effect creation is successful
  13915. * @param onError defines a function to call when the effect creation has failed
  13916. * @returns the new Effect
  13917. */
  13918. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13919. if (uniformsNames === void 0) { uniformsNames = []; }
  13920. if (samplers === void 0) { samplers = []; }
  13921. if (defines === void 0) { defines = ""; }
  13922. return this.createEffect({
  13923. vertex: "particles",
  13924. fragmentElement: fragmentName
  13925. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13926. };
  13927. /**
  13928. * Directly creates a webGL program
  13929. * @param vertexCode defines the vertex shader code to use
  13930. * @param fragmentCode defines the fragment shader code to use
  13931. * @param context defines the webGL context to use (if not set, the current one will be used)
  13932. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13933. * @returns the new webGL program
  13934. */
  13935. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13936. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13937. context = context || this._gl;
  13938. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13939. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13940. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13941. };
  13942. /**
  13943. * Creates a webGL program
  13944. * @param vertexCode defines the vertex shader code to use
  13945. * @param fragmentCode defines the fragment shader code to use
  13946. * @param defines defines the string containing the defines to use to compile the shaders
  13947. * @param context defines the webGL context to use (if not set, the current one will be used)
  13948. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13949. * @returns the new webGL program
  13950. */
  13951. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13952. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13953. context = context || this._gl;
  13954. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13955. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13956. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13957. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13958. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13959. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13960. return program;
  13961. };
  13962. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13963. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13964. var shaderProgram = context.createProgram();
  13965. if (!shaderProgram) {
  13966. throw new Error("Unable to create program");
  13967. }
  13968. context.attachShader(shaderProgram, vertexShader);
  13969. context.attachShader(shaderProgram, fragmentShader);
  13970. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13971. var transformFeedback = this.createTransformFeedback();
  13972. this.bindTransformFeedback(transformFeedback);
  13973. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13974. shaderProgram.transformFeedback = transformFeedback;
  13975. }
  13976. context.linkProgram(shaderProgram);
  13977. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13978. this.bindTransformFeedback(null);
  13979. }
  13980. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13981. if (!linked) {
  13982. context.validateProgram(shaderProgram);
  13983. var error = context.getProgramInfoLog(shaderProgram);
  13984. if (error) {
  13985. throw new Error(error);
  13986. }
  13987. }
  13988. context.deleteShader(vertexShader);
  13989. context.deleteShader(fragmentShader);
  13990. return shaderProgram;
  13991. };
  13992. /**
  13993. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13994. * @param shaderProgram defines the webGL program to use
  13995. * @param uniformsNames defines the list of uniform names
  13996. * @returns an array of webGL uniform locations
  13997. */
  13998. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13999. var results = new Array();
  14000. for (var index = 0; index < uniformsNames.length; index++) {
  14001. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14002. }
  14003. return results;
  14004. };
  14005. /**
  14006. * Gets the lsit of active attributes for a given webGL program
  14007. * @param shaderProgram defines the webGL program to use
  14008. * @param attributesNames defines the list of attribute names to get
  14009. * @returns an array of indices indicating the offset of each attribute
  14010. */
  14011. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14012. var results = [];
  14013. for (var index = 0; index < attributesNames.length; index++) {
  14014. try {
  14015. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14016. }
  14017. catch (e) {
  14018. results.push(-1);
  14019. }
  14020. }
  14021. return results;
  14022. };
  14023. /**
  14024. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14025. * @param effect defines the effect to activate
  14026. */
  14027. Engine.prototype.enableEffect = function (effect) {
  14028. if (!effect) {
  14029. return;
  14030. }
  14031. // Use program
  14032. this.bindSamplers(effect);
  14033. this._currentEffect = effect;
  14034. if (effect.onBind) {
  14035. effect.onBind(effect);
  14036. }
  14037. effect.onBindObservable.notifyObservers(effect);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to an array of int32
  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.setIntArray = function (uniform, array) {
  14045. if (!uniform)
  14046. return;
  14047. this._gl.uniform1iv(uniform, array);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to an array of int32 (stored as vec2)
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param array defines the array of int32 to store
  14053. */
  14054. Engine.prototype.setIntArray2 = function (uniform, array) {
  14055. if (!uniform || array.length % 2 !== 0)
  14056. return;
  14057. this._gl.uniform2iv(uniform, array);
  14058. };
  14059. /**
  14060. * Set the value of an uniform to an array of int32 (stored as vec3)
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param array defines the array of int32 to store
  14063. */
  14064. Engine.prototype.setIntArray3 = function (uniform, array) {
  14065. if (!uniform || array.length % 3 !== 0)
  14066. return;
  14067. this._gl.uniform3iv(uniform, array);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to an array of int32 (stored as vec4)
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param array defines the array of int32 to store
  14073. */
  14074. Engine.prototype.setIntArray4 = function (uniform, array) {
  14075. if (!uniform || array.length % 4 !== 0)
  14076. return;
  14077. this._gl.uniform4iv(uniform, array);
  14078. };
  14079. /**
  14080. * Set the value of an uniform to an array of float32
  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.setFloatArray = function (uniform, array) {
  14085. if (!uniform)
  14086. return;
  14087. this._gl.uniform1fv(uniform, array);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to an array of float32 (stored as vec2)
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param array defines the array of float32 to store
  14093. */
  14094. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14095. if (!uniform || array.length % 2 !== 0)
  14096. return;
  14097. this._gl.uniform2fv(uniform, array);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to an array of float32 (stored as vec3)
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param array defines the array of float32 to store
  14103. */
  14104. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14105. if (!uniform || array.length % 3 !== 0)
  14106. return;
  14107. this._gl.uniform3fv(uniform, array);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to an array of float32 (stored as vec4)
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param array defines the array of float32 to store
  14113. */
  14114. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14115. if (!uniform || array.length % 4 !== 0)
  14116. return;
  14117. this._gl.uniform4fv(uniform, array);
  14118. };
  14119. /**
  14120. * Set the value of an uniform to an array of number
  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.setArray = function (uniform, array) {
  14125. if (!uniform)
  14126. return;
  14127. this._gl.uniform1fv(uniform, array);
  14128. };
  14129. /**
  14130. * Set the value of an uniform to an array of number (stored as vec2)
  14131. * @param uniform defines the webGL uniform location where to store the value
  14132. * @param array defines the array of number to store
  14133. */
  14134. Engine.prototype.setArray2 = function (uniform, array) {
  14135. if (!uniform || array.length % 2 !== 0)
  14136. return;
  14137. this._gl.uniform2fv(uniform, array);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to an array of number (stored as vec3)
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param array defines the array of number to store
  14143. */
  14144. Engine.prototype.setArray3 = function (uniform, array) {
  14145. if (!uniform || array.length % 3 !== 0)
  14146. return;
  14147. this._gl.uniform3fv(uniform, array);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to an array of number (stored as vec4)
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param array defines the array of number to store
  14153. */
  14154. Engine.prototype.setArray4 = function (uniform, array) {
  14155. if (!uniform || array.length % 4 !== 0)
  14156. return;
  14157. this._gl.uniform4fv(uniform, array);
  14158. };
  14159. /**
  14160. * Set the value of an uniform to an array of float32 (stored as matrices)
  14161. * @param uniform defines the webGL uniform location where to store the value
  14162. * @param matrices defines the array of float32 to store
  14163. */
  14164. Engine.prototype.setMatrices = function (uniform, matrices) {
  14165. if (!uniform)
  14166. return;
  14167. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14168. };
  14169. /**
  14170. * Set the value of an uniform to a matrix
  14171. * @param uniform defines the webGL uniform location where to store the value
  14172. * @param matrix defines the matrix to store
  14173. */
  14174. Engine.prototype.setMatrix = function (uniform, matrix) {
  14175. if (!uniform)
  14176. return;
  14177. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14178. };
  14179. /**
  14180. * Set the value of an uniform to a matrix (3x3)
  14181. * @param uniform defines the webGL uniform location where to store the value
  14182. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14183. */
  14184. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14185. if (!uniform)
  14186. return;
  14187. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to a matrix (2x2)
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14193. */
  14194. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14195. if (!uniform)
  14196. return;
  14197. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14198. };
  14199. /**
  14200. * Set the value of an uniform to a number (int)
  14201. * @param uniform defines the webGL uniform location where to store the value
  14202. * @param value defines the int number to store
  14203. */
  14204. Engine.prototype.setInt = function (uniform, value) {
  14205. if (!uniform)
  14206. return;
  14207. this._gl.uniform1i(uniform, value);
  14208. };
  14209. /**
  14210. * Set the value of an uniform to a number (float)
  14211. * @param uniform defines the webGL uniform location where to store the value
  14212. * @param value defines the float number to store
  14213. */
  14214. Engine.prototype.setFloat = function (uniform, value) {
  14215. if (!uniform)
  14216. return;
  14217. this._gl.uniform1f(uniform, value);
  14218. };
  14219. /**
  14220. * Set the value of an uniform to a vec2
  14221. * @param uniform defines the webGL uniform location where to store the value
  14222. * @param x defines the 1st component of the value
  14223. * @param y defines the 2nd component of the value
  14224. */
  14225. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14226. if (!uniform)
  14227. return;
  14228. this._gl.uniform2f(uniform, x, y);
  14229. };
  14230. /**
  14231. * Set the value of an uniform to a vec3
  14232. * @param uniform defines the webGL uniform location where to store the value
  14233. * @param x defines the 1st component of the value
  14234. * @param y defines the 2nd component of the value
  14235. * @param z defines the 3rd component of the value
  14236. */
  14237. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14238. if (!uniform)
  14239. return;
  14240. this._gl.uniform3f(uniform, x, y, z);
  14241. };
  14242. /**
  14243. * Set the value of an uniform to a boolean
  14244. * @param uniform defines the webGL uniform location where to store the value
  14245. * @param bool defines the boolean to store
  14246. */
  14247. Engine.prototype.setBool = function (uniform, bool) {
  14248. if (!uniform)
  14249. return;
  14250. this._gl.uniform1i(uniform, bool);
  14251. };
  14252. /**
  14253. * Set the value of an uniform to a vec4
  14254. * @param uniform defines the webGL uniform location where to store the value
  14255. * @param x defines the 1st component of the value
  14256. * @param y defines the 2nd component of the value
  14257. * @param z defines the 3rd component of the value
  14258. * @param w defines the 4th component of the value
  14259. */
  14260. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14261. if (!uniform)
  14262. return;
  14263. this._gl.uniform4f(uniform, x, y, z, w);
  14264. };
  14265. /**
  14266. * Set the value of an uniform to a Color3
  14267. * @param uniform defines the webGL uniform location where to store the value
  14268. * @param color3 defines the color to store
  14269. */
  14270. Engine.prototype.setColor3 = function (uniform, color3) {
  14271. if (!uniform)
  14272. return;
  14273. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14274. };
  14275. /**
  14276. * Set the value of an uniform to a Color3 and an alpha value
  14277. * @param uniform defines the webGL uniform location where to store the value
  14278. * @param color3 defines the color to store
  14279. * @param alpha defines the alpha component to store
  14280. */
  14281. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14282. if (!uniform)
  14283. return;
  14284. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14285. };
  14286. /**
  14287. * Sets a Color4 on a uniform variable
  14288. * @param uniform defines the uniform location
  14289. * @param color4 defines the value to be set
  14290. */
  14291. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14292. if (!uniform)
  14293. return;
  14294. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14295. };
  14296. // States
  14297. /**
  14298. * Set various states to the webGL context
  14299. * @param culling defines backface culling state
  14300. * @param zOffset defines the value to apply to zOffset (0 by default)
  14301. * @param force defines if states must be applied even if cache is up to date
  14302. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14303. */
  14304. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14305. if (zOffset === void 0) { zOffset = 0; }
  14306. if (reverseSide === void 0) { reverseSide = false; }
  14307. // Culling
  14308. if (this._depthCullingState.cull !== culling || force) {
  14309. this._depthCullingState.cull = culling;
  14310. }
  14311. // Cull face
  14312. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14313. if (this._depthCullingState.cullFace !== cullFace || force) {
  14314. this._depthCullingState.cullFace = cullFace;
  14315. }
  14316. // Z offset
  14317. this.setZOffset(zOffset);
  14318. // Front face
  14319. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14320. if (this._depthCullingState.frontFace !== frontFace || force) {
  14321. this._depthCullingState.frontFace = frontFace;
  14322. }
  14323. };
  14324. /**
  14325. * Set the z offset to apply to current rendering
  14326. * @param value defines the offset to apply
  14327. */
  14328. Engine.prototype.setZOffset = function (value) {
  14329. this._depthCullingState.zOffset = value;
  14330. };
  14331. /**
  14332. * Gets the current value of the zOffset
  14333. * @returns the current zOffset state
  14334. */
  14335. Engine.prototype.getZOffset = function () {
  14336. return this._depthCullingState.zOffset;
  14337. };
  14338. /**
  14339. * Enable or disable depth buffering
  14340. * @param enable defines the state to set
  14341. */
  14342. Engine.prototype.setDepthBuffer = function (enable) {
  14343. this._depthCullingState.depthTest = enable;
  14344. };
  14345. /**
  14346. * Gets a boolean indicating if depth writing is enabled
  14347. * @returns the current depth writing state
  14348. */
  14349. Engine.prototype.getDepthWrite = function () {
  14350. return this._depthCullingState.depthMask;
  14351. };
  14352. /**
  14353. * Enable or disable depth writing
  14354. * @param enable defines the state to set
  14355. */
  14356. Engine.prototype.setDepthWrite = function (enable) {
  14357. this._depthCullingState.depthMask = enable;
  14358. };
  14359. /**
  14360. * Enable or disable color writing
  14361. * @param enable defines the state to set
  14362. */
  14363. Engine.prototype.setColorWrite = function (enable) {
  14364. this._gl.colorMask(enable, enable, enable, enable);
  14365. this._colorWrite = enable;
  14366. };
  14367. /**
  14368. * Gets a boolean indicating if color writing is enabled
  14369. * @returns the current color writing state
  14370. */
  14371. Engine.prototype.getColorWrite = function () {
  14372. return this._colorWrite;
  14373. };
  14374. /**
  14375. * Sets alpha constants used by some alpha blending modes
  14376. * @param r defines the red component
  14377. * @param g defines the green component
  14378. * @param b defines the blue component
  14379. * @param a defines the alpha component
  14380. */
  14381. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14382. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14383. };
  14384. /**
  14385. * Sets the current alpha mode
  14386. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14387. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14388. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14389. */
  14390. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14391. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14392. if (this._alphaMode === mode) {
  14393. return;
  14394. }
  14395. switch (mode) {
  14396. case Engine.ALPHA_DISABLE:
  14397. this._alphaState.alphaBlend = false;
  14398. break;
  14399. case Engine.ALPHA_PREMULTIPLIED:
  14400. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14401. this._alphaState.alphaBlend = true;
  14402. break;
  14403. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14404. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14405. this._alphaState.alphaBlend = true;
  14406. break;
  14407. case Engine.ALPHA_COMBINE:
  14408. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14409. this._alphaState.alphaBlend = true;
  14410. break;
  14411. case Engine.ALPHA_ONEONE:
  14412. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14413. this._alphaState.alphaBlend = true;
  14414. break;
  14415. case Engine.ALPHA_ADD:
  14416. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14417. this._alphaState.alphaBlend = true;
  14418. break;
  14419. case Engine.ALPHA_SUBTRACT:
  14420. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14421. this._alphaState.alphaBlend = true;
  14422. break;
  14423. case Engine.ALPHA_MULTIPLY:
  14424. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14425. this._alphaState.alphaBlend = true;
  14426. break;
  14427. case Engine.ALPHA_MAXIMIZED:
  14428. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14429. this._alphaState.alphaBlend = true;
  14430. break;
  14431. case Engine.ALPHA_INTERPOLATE:
  14432. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14433. this._alphaState.alphaBlend = true;
  14434. break;
  14435. case Engine.ALPHA_SCREENMODE:
  14436. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14437. this._alphaState.alphaBlend = true;
  14438. break;
  14439. }
  14440. if (!noDepthWriteChange) {
  14441. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14442. }
  14443. this._alphaMode = mode;
  14444. };
  14445. /**
  14446. * Gets the current alpha mode
  14447. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14448. * @returns the current alpha mode
  14449. */
  14450. Engine.prototype.getAlphaMode = function () {
  14451. return this._alphaMode;
  14452. };
  14453. // Textures
  14454. /**
  14455. * Force the entire cache to be cleared
  14456. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14457. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14458. */
  14459. Engine.prototype.wipeCaches = function (bruteForce) {
  14460. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14461. return;
  14462. }
  14463. this._currentEffect = null;
  14464. if (bruteForce) {
  14465. this.resetTextureCache();
  14466. this._currentProgram = null;
  14467. this._stencilState.reset();
  14468. this._depthCullingState.reset();
  14469. this.setDepthFunctionToLessOrEqual();
  14470. this._alphaState.reset();
  14471. }
  14472. this._resetVertexBufferBinding();
  14473. this._cachedIndexBuffer = null;
  14474. this._cachedEffectForVertexBuffers = null;
  14475. this._unbindVertexArrayObject();
  14476. this.bindIndexBuffer(null);
  14477. };
  14478. /**
  14479. * Set the compressed texture format to use, based on the formats you have, and the formats
  14480. * supported by the hardware / browser.
  14481. *
  14482. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14483. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14484. * to API arguments needed to compressed textures. This puts the burden on the container
  14485. * generator to house the arcane code for determining these for current & future formats.
  14486. *
  14487. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14488. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14489. *
  14490. * Note: The result of this call is not taken into account when a texture is base64.
  14491. *
  14492. * @param formatsAvailable defines the list of those format families you have created
  14493. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14494. *
  14495. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14496. * @returns The extension selected.
  14497. */
  14498. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14499. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14500. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14501. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14502. return this._textureFormatInUse = this._texturesSupported[i];
  14503. }
  14504. }
  14505. }
  14506. // actively set format to nothing, to allow this to be called more than once
  14507. // and possibly fail the 2nd time
  14508. this._textureFormatInUse = null;
  14509. return null;
  14510. };
  14511. /** @hidden */
  14512. Engine.prototype._createTexture = function () {
  14513. var texture = this._gl.createTexture();
  14514. if (!texture) {
  14515. throw new Error("Unable to create texture");
  14516. }
  14517. return texture;
  14518. };
  14519. /**
  14520. * Usually called from BABYLON.Texture.ts.
  14521. * Passed information to create a WebGLTexture
  14522. * @param urlArg defines a value which contains one of the following:
  14523. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14524. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14525. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14526. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14527. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14528. * @param scene needed for loading to the correct scene
  14529. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14530. * @param onLoad optional callback to be called upon successful completion
  14531. * @param onError optional callback to be called upon failure
  14532. * @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
  14533. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14534. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14535. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14536. */
  14537. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14538. var _this = this;
  14539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14540. if (onLoad === void 0) { onLoad = null; }
  14541. if (onError === void 0) { onError = null; }
  14542. if (buffer === void 0) { buffer = null; }
  14543. if (fallback === void 0) { fallback = null; }
  14544. if (format === void 0) { format = null; }
  14545. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14546. var fromData = url.substr(0, 5) === "data:";
  14547. var fromBlob = url.substr(0, 5) === "blob:";
  14548. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14549. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14550. // establish the file extension, if possible
  14551. var lastDot = url.lastIndexOf('.');
  14552. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14553. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14554. var isTGA = (extension.indexOf(".tga") === 0);
  14555. // determine if a ktx file should be substituted
  14556. var isKTX = false;
  14557. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14558. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14559. isKTX = true;
  14560. }
  14561. if (scene) {
  14562. scene._addPendingData(texture);
  14563. }
  14564. texture.url = url;
  14565. texture.generateMipMaps = !noMipmap;
  14566. texture.samplingMode = samplingMode;
  14567. texture.invertY = invertY;
  14568. if (!this._doNotHandleContextLost) {
  14569. // Keep a link to the buffer only if we plan to handle context lost
  14570. texture._buffer = buffer;
  14571. }
  14572. var onLoadObserver = null;
  14573. if (onLoad && !fallback) {
  14574. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14575. }
  14576. if (!fallback)
  14577. this._internalTexturesCache.push(texture);
  14578. var onerror = function (message, exception) {
  14579. if (scene) {
  14580. scene._removePendingData(texture);
  14581. }
  14582. if (onLoadObserver) {
  14583. texture.onLoadedObservable.remove(onLoadObserver);
  14584. }
  14585. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14586. if (isKTX) {
  14587. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14588. }
  14589. else if (BABYLON.Tools.UseFallbackTexture) {
  14590. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14591. }
  14592. if (onError) {
  14593. onError(message || "Unknown error", exception);
  14594. }
  14595. };
  14596. var callback = null;
  14597. // processing for non-image formats
  14598. if (isKTX || isTGA || isDDS) {
  14599. if (isKTX) {
  14600. callback = function (data) {
  14601. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14602. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14603. ktx.uploadLevels(_this._gl, !noMipmap);
  14604. return false;
  14605. }, samplingMode);
  14606. };
  14607. }
  14608. else if (isTGA) {
  14609. callback = function (arrayBuffer) {
  14610. var data = new Uint8Array(arrayBuffer);
  14611. var header = BABYLON.TGATools.GetTGAHeader(data);
  14612. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14613. BABYLON.TGATools.UploadContent(_this._gl, data);
  14614. return false;
  14615. }, samplingMode);
  14616. };
  14617. }
  14618. else if (isDDS) {
  14619. callback = function (data) {
  14620. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14621. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14622. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14623. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14624. return false;
  14625. }, samplingMode);
  14626. };
  14627. }
  14628. if (!buffer) {
  14629. this._loadFile(url, function (data) {
  14630. if (callback) {
  14631. callback(data);
  14632. }
  14633. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14634. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14635. });
  14636. }
  14637. else {
  14638. if (callback) {
  14639. callback(buffer);
  14640. }
  14641. }
  14642. // image format processing
  14643. }
  14644. else {
  14645. var onload = function (img) {
  14646. if (fromBlob && !_this._doNotHandleContextLost) {
  14647. // We need to store the image if we need to rebuild the texture
  14648. // in case of a webgl context lost
  14649. texture._buffer = img;
  14650. }
  14651. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14652. var gl = _this._gl;
  14653. var isPot = (img.width === potWidth && img.height === potHeight);
  14654. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14655. if (isPot) {
  14656. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14657. return false;
  14658. }
  14659. // Using shaders to rescale because canvas.drawImage is lossy
  14660. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14661. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14662. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14663. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14664. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14665. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14666. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14667. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14668. _this._releaseTexture(source);
  14669. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14670. continuationCallback();
  14671. });
  14672. return true;
  14673. }, samplingMode);
  14674. };
  14675. if (!fromData || isBase64) {
  14676. if (buffer instanceof HTMLImageElement) {
  14677. onload(buffer);
  14678. }
  14679. else {
  14680. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14681. }
  14682. }
  14683. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14684. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14685. }
  14686. else {
  14687. onload(buffer);
  14688. }
  14689. }
  14690. return texture;
  14691. };
  14692. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14693. var _this = this;
  14694. var rtt = this.createRenderTargetTexture({
  14695. width: destination.width,
  14696. height: destination.height,
  14697. }, {
  14698. generateMipMaps: false,
  14699. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14700. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14701. generateDepthBuffer: false,
  14702. generateStencilBuffer: false
  14703. });
  14704. if (!this._rescalePostProcess) {
  14705. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14706. }
  14707. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14708. _this._rescalePostProcess.onApply = function (effect) {
  14709. effect._bindTexture("textureSampler", source);
  14710. };
  14711. var hostingScene = scene;
  14712. if (!hostingScene) {
  14713. hostingScene = _this.scenes[_this.scenes.length - 1];
  14714. }
  14715. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14716. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14717. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14718. _this.unBindFramebuffer(rtt);
  14719. _this._releaseTexture(rtt);
  14720. if (onComplete) {
  14721. onComplete();
  14722. }
  14723. });
  14724. };
  14725. /**
  14726. * Update a raw texture
  14727. * @param texture defines the texture to update
  14728. * @param data defines the data to store in the texture
  14729. * @param format defines the format of the data
  14730. * @param invertY defines if data must be stored with Y axis inverted
  14731. * @param compression defines the compression used (null by default)
  14732. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14733. */
  14734. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14735. if (compression === void 0) { compression = null; }
  14736. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14737. if (!texture) {
  14738. return;
  14739. }
  14740. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14741. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14742. // babylon's internalFormat but gl's texImage2D format
  14743. var internalFormat = this._getInternalFormat(format);
  14744. var textureType = this._getWebGLTextureType(type);
  14745. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14746. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14747. if (!this._doNotHandleContextLost) {
  14748. texture._bufferView = data;
  14749. texture.format = format;
  14750. texture.type = type;
  14751. texture.invertY = invertY;
  14752. texture._compression = compression;
  14753. }
  14754. if (texture.width % 4 !== 0) {
  14755. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14756. }
  14757. if (compression && data) {
  14758. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14759. }
  14760. else {
  14761. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14762. }
  14763. if (texture.generateMipMaps) {
  14764. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14765. }
  14766. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14767. // this.resetTextureCache();
  14768. texture.isReady = true;
  14769. };
  14770. /**
  14771. * Creates a raw texture
  14772. * @param data defines the data to store in the texture
  14773. * @param width defines the width of the texture
  14774. * @param height defines the height of the texture
  14775. * @param format defines the format of the data
  14776. * @param generateMipMaps defines if the engine should generate the mip levels
  14777. * @param invertY defines if data must be stored with Y axis inverted
  14778. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14779. * @param compression defines the compression used (null by default)
  14780. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14781. * @returns the raw texture inside an InternalTexture
  14782. */
  14783. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14784. if (compression === void 0) { compression = null; }
  14785. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14786. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14787. texture.baseWidth = width;
  14788. texture.baseHeight = height;
  14789. texture.width = width;
  14790. texture.height = height;
  14791. texture.format = format;
  14792. texture.generateMipMaps = generateMipMaps;
  14793. texture.samplingMode = samplingMode;
  14794. texture.invertY = invertY;
  14795. texture._compression = compression;
  14796. texture.type = type;
  14797. if (!this._doNotHandleContextLost) {
  14798. texture._bufferView = data;
  14799. }
  14800. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14801. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14802. // Filters
  14803. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14804. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14805. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14806. if (generateMipMaps) {
  14807. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14808. }
  14809. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14810. this._internalTexturesCache.push(texture);
  14811. return texture;
  14812. };
  14813. /**
  14814. * Creates a dynamic texture
  14815. * @param width defines the width of the texture
  14816. * @param height defines the height of the texture
  14817. * @param generateMipMaps defines if the engine should generate the mip levels
  14818. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14819. * @returns the dynamic texture inside an InternalTexture
  14820. */
  14821. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14822. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14823. texture.baseWidth = width;
  14824. texture.baseHeight = height;
  14825. if (generateMipMaps) {
  14826. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14827. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14828. }
  14829. // this.resetTextureCache();
  14830. texture.width = width;
  14831. texture.height = height;
  14832. texture.isReady = false;
  14833. texture.generateMipMaps = generateMipMaps;
  14834. texture.samplingMode = samplingMode;
  14835. this.updateTextureSamplingMode(samplingMode, texture);
  14836. this._internalTexturesCache.push(texture);
  14837. return texture;
  14838. };
  14839. /**
  14840. * Update the sampling mode of a given texture
  14841. * @param samplingMode defines the required sampling mode
  14842. * @param texture defines the texture to update
  14843. */
  14844. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14845. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14846. if (texture.isCube) {
  14847. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14848. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14849. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14850. }
  14851. else if (texture.is3D) {
  14852. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14853. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14854. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14855. }
  14856. else {
  14857. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14858. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14859. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14860. }
  14861. texture.samplingMode = samplingMode;
  14862. };
  14863. /**
  14864. * Update the content of a dynamic texture
  14865. * @param texture defines the texture to update
  14866. * @param canvas defines the canvas containing the source
  14867. * @param invertY defines if data must be stored with Y axis inverted
  14868. * @param premulAlpha defines if alpha is stored as premultiplied
  14869. * @param format defines the format of the data
  14870. */
  14871. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14872. if (premulAlpha === void 0) { premulAlpha = false; }
  14873. if (!texture) {
  14874. return;
  14875. }
  14876. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14877. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14878. if (premulAlpha) {
  14879. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14880. }
  14881. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14882. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14883. if (texture.generateMipMaps) {
  14884. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14885. }
  14886. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14887. if (premulAlpha) {
  14888. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14889. }
  14890. texture.isReady = true;
  14891. };
  14892. /**
  14893. * Update a video texture
  14894. * @param texture defines the texture to update
  14895. * @param video defines the video element to use
  14896. * @param invertY defines if data must be stored with Y axis inverted
  14897. */
  14898. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14899. if (!texture || texture._isDisabled) {
  14900. return;
  14901. }
  14902. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14903. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14904. try {
  14905. // Testing video texture support
  14906. if (this._videoTextureSupported === undefined) {
  14907. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14908. if (this._gl.getError() !== 0) {
  14909. this._videoTextureSupported = false;
  14910. }
  14911. else {
  14912. this._videoTextureSupported = true;
  14913. }
  14914. }
  14915. // Copy video through the current working canvas if video texture is not supported
  14916. if (!this._videoTextureSupported) {
  14917. if (!texture._workingCanvas) {
  14918. texture._workingCanvas = document.createElement("canvas");
  14919. var context = texture._workingCanvas.getContext("2d");
  14920. if (!context) {
  14921. throw new Error("Unable to get 2d context");
  14922. }
  14923. texture._workingContext = context;
  14924. texture._workingCanvas.width = texture.width;
  14925. texture._workingCanvas.height = texture.height;
  14926. }
  14927. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14928. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14929. }
  14930. else {
  14931. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14932. }
  14933. if (texture.generateMipMaps) {
  14934. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14935. }
  14936. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14937. // this.resetTextureCache();
  14938. texture.isReady = true;
  14939. }
  14940. catch (ex) {
  14941. // Something unexpected
  14942. // Let's disable the texture
  14943. texture._isDisabled = true;
  14944. }
  14945. };
  14946. /**
  14947. * Updates a depth texture Comparison Mode and Function.
  14948. * If the comparison Function is equal to 0, the mode will be set to none.
  14949. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14950. * @param texture The texture to set the comparison function for
  14951. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14952. */
  14953. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14954. if (this.webGLVersion === 1) {
  14955. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14956. return;
  14957. }
  14958. var gl = this._gl;
  14959. if (texture.isCube) {
  14960. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14961. if (comparisonFunction === 0) {
  14962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14964. }
  14965. else {
  14966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14968. }
  14969. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14970. }
  14971. else {
  14972. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14973. if (comparisonFunction === 0) {
  14974. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14975. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14976. }
  14977. else {
  14978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14980. }
  14981. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14982. }
  14983. texture._comparisonFunction = comparisonFunction;
  14984. };
  14985. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14986. var width = size.width || size;
  14987. var height = size.height || size;
  14988. internalTexture.baseWidth = width;
  14989. internalTexture.baseHeight = height;
  14990. internalTexture.width = width;
  14991. internalTexture.height = height;
  14992. internalTexture.isReady = true;
  14993. internalTexture.samples = 1;
  14994. internalTexture.generateMipMaps = false;
  14995. internalTexture._generateDepthBuffer = true;
  14996. internalTexture._generateStencilBuffer = generateStencil;
  14997. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14998. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14999. internalTexture._comparisonFunction = comparisonFunction;
  15000. var gl = this._gl;
  15001. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15002. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15003. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15004. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15005. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15006. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15007. if (comparisonFunction === 0) {
  15008. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15009. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15010. }
  15011. else {
  15012. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15013. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15014. }
  15015. };
  15016. /**
  15017. * Creates a depth stencil texture.
  15018. * This is only available in WebGL 2 or with the depth texture extension available.
  15019. * @param size The size of face edge in the texture.
  15020. * @param options The options defining the texture.
  15021. * @returns The texture
  15022. */
  15023. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15024. if (options.isCube) {
  15025. var width = size.width || size;
  15026. return this._createDepthStencilCubeTexture(width, options);
  15027. }
  15028. else {
  15029. return this._createDepthStencilTexture(size, options);
  15030. }
  15031. };
  15032. /**
  15033. * Creates a depth stencil texture.
  15034. * This is only available in WebGL 2 or with the depth texture extension available.
  15035. * @param size The size of face edge in the texture.
  15036. * @param options The options defining the texture.
  15037. * @returns The texture
  15038. */
  15039. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15040. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15041. if (!this._caps.depthTextureExtension) {
  15042. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15043. return internalTexture;
  15044. }
  15045. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15046. var gl = this._gl;
  15047. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15048. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15049. if (this.webGLVersion > 1) {
  15050. if (internalOptions.generateStencil) {
  15051. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15052. }
  15053. else {
  15054. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15055. }
  15056. }
  15057. else {
  15058. if (internalOptions.generateStencil) {
  15059. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15060. }
  15061. else {
  15062. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15063. }
  15064. }
  15065. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15066. return internalTexture;
  15067. };
  15068. /**
  15069. * Creates a depth stencil cube texture.
  15070. * This is only available in WebGL 2.
  15071. * @param size The size of face edge in the cube texture.
  15072. * @param options The options defining the cube texture.
  15073. * @returns The cube texture
  15074. */
  15075. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15076. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15077. internalTexture.isCube = true;
  15078. if (this.webGLVersion === 1) {
  15079. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15080. return internalTexture;
  15081. }
  15082. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15083. var gl = this._gl;
  15084. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15085. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15086. // Create the depth/stencil buffer
  15087. for (var face = 0; face < 6; face++) {
  15088. if (internalOptions.generateStencil) {
  15089. 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);
  15090. }
  15091. else {
  15092. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15093. }
  15094. }
  15095. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15096. return internalTexture;
  15097. };
  15098. /**
  15099. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15100. * @param renderTarget The render target to set the frame buffer for
  15101. */
  15102. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15103. // Create the framebuffer
  15104. var internalTexture = renderTarget.getInternalTexture();
  15105. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15106. return;
  15107. }
  15108. var gl = this._gl;
  15109. var depthStencilTexture = renderTarget.depthStencilTexture;
  15110. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15111. if (depthStencilTexture.isCube) {
  15112. if (depthStencilTexture._generateStencilBuffer) {
  15113. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15114. }
  15115. else {
  15116. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15117. }
  15118. }
  15119. else {
  15120. if (depthStencilTexture._generateStencilBuffer) {
  15121. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15122. }
  15123. else {
  15124. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15125. }
  15126. }
  15127. this.bindUnboundFramebuffer(null);
  15128. };
  15129. /**
  15130. * Creates a new render target texture
  15131. * @param size defines the size of the texture
  15132. * @param options defines the options used to create the texture
  15133. * @returns a new render target texture stored in an InternalTexture
  15134. */
  15135. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15136. var fullOptions = new RenderTargetCreationOptions();
  15137. if (options !== undefined && typeof options === "object") {
  15138. fullOptions.generateMipMaps = options.generateMipMaps;
  15139. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15140. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15141. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15142. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15143. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15144. }
  15145. else {
  15146. fullOptions.generateMipMaps = options;
  15147. fullOptions.generateDepthBuffer = true;
  15148. fullOptions.generateStencilBuffer = false;
  15149. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15150. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15151. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15152. }
  15153. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15154. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15155. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15156. }
  15157. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15158. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15159. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15160. }
  15161. var gl = this._gl;
  15162. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15163. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15164. var width = size.width || size;
  15165. var height = size.height || size;
  15166. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15167. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15168. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15169. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15170. }
  15171. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15175. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15176. // Create the framebuffer
  15177. var currentFrameBuffer = this._currentFramebuffer;
  15178. var framebuffer = gl.createFramebuffer();
  15179. this.bindUnboundFramebuffer(framebuffer);
  15180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15181. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15182. if (fullOptions.generateMipMaps) {
  15183. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15184. }
  15185. // Unbind
  15186. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15187. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15188. this.bindUnboundFramebuffer(currentFrameBuffer);
  15189. texture._framebuffer = framebuffer;
  15190. texture.baseWidth = width;
  15191. texture.baseHeight = height;
  15192. texture.width = width;
  15193. texture.height = height;
  15194. texture.isReady = true;
  15195. texture.samples = 1;
  15196. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15197. texture.samplingMode = fullOptions.samplingMode;
  15198. texture.type = fullOptions.type;
  15199. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15200. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15201. // this.resetTextureCache();
  15202. this._internalTexturesCache.push(texture);
  15203. return texture;
  15204. };
  15205. /**
  15206. * Create a multi render target texture
  15207. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15208. * @param size defines the size of the texture
  15209. * @param options defines the creation options
  15210. * @returns the cube texture as an InternalTexture
  15211. */
  15212. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15213. var generateMipMaps = false;
  15214. var generateDepthBuffer = true;
  15215. var generateStencilBuffer = false;
  15216. var generateDepthTexture = false;
  15217. var textureCount = 1;
  15218. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15219. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15220. var types = new Array();
  15221. var samplingModes = new Array();
  15222. if (options !== undefined) {
  15223. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15224. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15225. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15226. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15227. textureCount = options.textureCount || 1;
  15228. if (options.types) {
  15229. types = options.types;
  15230. }
  15231. if (options.samplingModes) {
  15232. samplingModes = options.samplingModes;
  15233. }
  15234. }
  15235. var gl = this._gl;
  15236. // Create the framebuffer
  15237. var framebuffer = gl.createFramebuffer();
  15238. this.bindUnboundFramebuffer(framebuffer);
  15239. var width = size.width || size;
  15240. var height = size.height || size;
  15241. var textures = [];
  15242. var attachments = [];
  15243. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15244. for (var i = 0; i < textureCount; i++) {
  15245. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15246. var type = types[i] || defaultType;
  15247. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15248. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15249. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15250. }
  15251. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15252. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15253. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15254. }
  15255. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15256. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15257. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15258. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15259. }
  15260. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15261. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15262. textures.push(texture);
  15263. attachments.push(attachment);
  15264. gl.activeTexture(gl["TEXTURE" + i]);
  15265. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15270. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15271. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15272. if (generateMipMaps) {
  15273. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15274. }
  15275. // Unbind
  15276. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15277. texture._framebuffer = framebuffer;
  15278. texture._depthStencilBuffer = depthStencilBuffer;
  15279. texture.baseWidth = width;
  15280. texture.baseHeight = height;
  15281. texture.width = width;
  15282. texture.height = height;
  15283. texture.isReady = true;
  15284. texture.samples = 1;
  15285. texture.generateMipMaps = generateMipMaps;
  15286. texture.samplingMode = samplingMode;
  15287. texture.type = type;
  15288. texture._generateDepthBuffer = generateDepthBuffer;
  15289. texture._generateStencilBuffer = generateStencilBuffer;
  15290. texture._attachments = attachments;
  15291. this._internalTexturesCache.push(texture);
  15292. }
  15293. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15294. // Depth texture
  15295. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15296. gl.activeTexture(gl.TEXTURE0);
  15297. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15302. 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);
  15303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15304. depthTexture._framebuffer = framebuffer;
  15305. depthTexture.baseWidth = width;
  15306. depthTexture.baseHeight = height;
  15307. depthTexture.width = width;
  15308. depthTexture.height = height;
  15309. depthTexture.isReady = true;
  15310. depthTexture.samples = 1;
  15311. depthTexture.generateMipMaps = generateMipMaps;
  15312. depthTexture.samplingMode = gl.NEAREST;
  15313. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15314. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15315. textures.push(depthTexture);
  15316. this._internalTexturesCache.push(depthTexture);
  15317. }
  15318. gl.drawBuffers(attachments);
  15319. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15320. this.bindUnboundFramebuffer(null);
  15321. this.resetTextureCache();
  15322. return textures;
  15323. };
  15324. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15325. if (samples === void 0) { samples = 1; }
  15326. var depthStencilBuffer = null;
  15327. var gl = this._gl;
  15328. // Create the depth/stencil buffer
  15329. if (generateStencilBuffer) {
  15330. depthStencilBuffer = gl.createRenderbuffer();
  15331. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15332. if (samples > 1) {
  15333. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15334. }
  15335. else {
  15336. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15337. }
  15338. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15339. }
  15340. else if (generateDepthBuffer) {
  15341. depthStencilBuffer = gl.createRenderbuffer();
  15342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15343. if (samples > 1) {
  15344. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15345. }
  15346. else {
  15347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15348. }
  15349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15350. }
  15351. return depthStencilBuffer;
  15352. };
  15353. /**
  15354. * Updates the sample count of a render target texture
  15355. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15356. * @param texture defines the texture to update
  15357. * @param samples defines the sample count to set
  15358. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15359. */
  15360. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15361. if (this.webGLVersion < 2 || !texture) {
  15362. return 1;
  15363. }
  15364. if (texture.samples === samples) {
  15365. return samples;
  15366. }
  15367. var gl = this._gl;
  15368. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15369. // Dispose previous render buffers
  15370. if (texture._depthStencilBuffer) {
  15371. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15372. texture._depthStencilBuffer = null;
  15373. }
  15374. if (texture._MSAAFramebuffer) {
  15375. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15376. texture._MSAAFramebuffer = null;
  15377. }
  15378. if (texture._MSAARenderBuffer) {
  15379. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15380. texture._MSAARenderBuffer = null;
  15381. }
  15382. if (samples > 1) {
  15383. var framebuffer = gl.createFramebuffer();
  15384. if (!framebuffer) {
  15385. throw new Error("Unable to create multi sampled framebuffer");
  15386. }
  15387. texture._MSAAFramebuffer = framebuffer;
  15388. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15389. var colorRenderbuffer = gl.createRenderbuffer();
  15390. if (!colorRenderbuffer) {
  15391. throw new Error("Unable to create multi sampled framebuffer");
  15392. }
  15393. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15394. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15395. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15396. texture._MSAARenderBuffer = colorRenderbuffer;
  15397. }
  15398. else {
  15399. this.bindUnboundFramebuffer(texture._framebuffer);
  15400. }
  15401. texture.samples = samples;
  15402. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15403. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15404. this.bindUnboundFramebuffer(null);
  15405. return samples;
  15406. };
  15407. /**
  15408. * Update the sample count for a given multiple render target texture
  15409. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15410. * @param textures defines the textures to update
  15411. * @param samples defines the sample count to set
  15412. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15413. */
  15414. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15415. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15416. return 1;
  15417. }
  15418. if (textures[0].samples === samples) {
  15419. return samples;
  15420. }
  15421. var gl = this._gl;
  15422. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15423. // Dispose previous render buffers
  15424. if (textures[0]._depthStencilBuffer) {
  15425. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15426. textures[0]._depthStencilBuffer = null;
  15427. }
  15428. if (textures[0]._MSAAFramebuffer) {
  15429. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15430. textures[0]._MSAAFramebuffer = null;
  15431. }
  15432. for (var i = 0; i < textures.length; i++) {
  15433. if (textures[i]._MSAARenderBuffer) {
  15434. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15435. textures[i]._MSAARenderBuffer = null;
  15436. }
  15437. }
  15438. if (samples > 1) {
  15439. var framebuffer = gl.createFramebuffer();
  15440. if (!framebuffer) {
  15441. throw new Error("Unable to create multi sampled framebuffer");
  15442. }
  15443. this.bindUnboundFramebuffer(framebuffer);
  15444. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15445. var attachments = [];
  15446. for (var i = 0; i < textures.length; i++) {
  15447. var texture = textures[i];
  15448. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15449. var colorRenderbuffer = gl.createRenderbuffer();
  15450. if (!colorRenderbuffer) {
  15451. throw new Error("Unable to create multi sampled framebuffer");
  15452. }
  15453. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15454. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15455. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15456. texture._MSAAFramebuffer = framebuffer;
  15457. texture._MSAARenderBuffer = colorRenderbuffer;
  15458. texture.samples = samples;
  15459. texture._depthStencilBuffer = depthStencilBuffer;
  15460. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15461. attachments.push(attachment);
  15462. }
  15463. gl.drawBuffers(attachments);
  15464. }
  15465. else {
  15466. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15467. }
  15468. this.bindUnboundFramebuffer(null);
  15469. return samples;
  15470. };
  15471. /** @hidden */
  15472. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15473. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15474. };
  15475. /** @hidden */
  15476. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15477. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15478. };
  15479. /** @hidden */
  15480. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15481. var gl = this._gl;
  15482. var textureType = this._getWebGLTextureType(texture.type);
  15483. var format = this._getInternalFormat(texture.format);
  15484. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15485. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15486. this._bindTextureDirectly(bindTarget, texture, true);
  15487. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.invertY ? 1 : 0);
  15488. var target = gl.TEXTURE_2D;
  15489. if (texture.isCube) {
  15490. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15491. }
  15492. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15493. this._bindTextureDirectly(bindTarget, null, true);
  15494. };
  15495. /**
  15496. * Creates a new render target cube texture
  15497. * @param size defines the size of the texture
  15498. * @param options defines the options used to create the texture
  15499. * @returns a new render target cube texture stored in an InternalTexture
  15500. */
  15501. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15502. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15503. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15504. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15505. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15506. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15507. }
  15508. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15509. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15510. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15511. }
  15512. var gl = this._gl;
  15513. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15514. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15515. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15516. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15517. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15518. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15519. }
  15520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15522. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15523. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15524. for (var face = 0; face < 6; face++) {
  15525. 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);
  15526. }
  15527. // Create the framebuffer
  15528. var framebuffer = gl.createFramebuffer();
  15529. this.bindUnboundFramebuffer(framebuffer);
  15530. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15531. // MipMaps
  15532. if (fullOptions.generateMipMaps) {
  15533. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15534. }
  15535. // Unbind
  15536. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15537. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15538. this.bindUnboundFramebuffer(null);
  15539. texture._framebuffer = framebuffer;
  15540. texture.width = size;
  15541. texture.height = size;
  15542. texture.isReady = true;
  15543. texture.isCube = true;
  15544. texture.samples = 1;
  15545. texture.generateMipMaps = fullOptions.generateMipMaps;
  15546. texture.samplingMode = fullOptions.samplingMode;
  15547. texture.type = fullOptions.type;
  15548. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15549. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15550. this._internalTexturesCache.push(texture);
  15551. return texture;
  15552. };
  15553. /**
  15554. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15555. * @param rootUrl defines the url where the file to load is located
  15556. * @param scene defines the current scene
  15557. * @param lodScale defines scale to apply to the mip map selection
  15558. * @param lodOffset defines offset to apply to the mip map selection
  15559. * @param onLoad defines an optional callback raised when the texture is loaded
  15560. * @param onError defines an optional callback raised if there is an issue to load the texture
  15561. * @param format defines the format of the data
  15562. * @param forcedExtension defines the extension to use to pick the right loader
  15563. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15564. * @returns the cube texture as an InternalTexture
  15565. */
  15566. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15567. var _this = this;
  15568. if (onLoad === void 0) { onLoad = null; }
  15569. if (onError === void 0) { onError = null; }
  15570. if (forcedExtension === void 0) { forcedExtension = null; }
  15571. if (createPolynomials === void 0) { createPolynomials = true; }
  15572. var callback = function (loadData) {
  15573. if (!loadData) {
  15574. if (onLoad) {
  15575. onLoad(null);
  15576. }
  15577. return;
  15578. }
  15579. var texture = loadData.texture;
  15580. if (!createPolynomials) {
  15581. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15582. }
  15583. else if (loadData.info.sphericalPolynomial) {
  15584. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15585. }
  15586. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15587. if (_this._caps.textureLOD) {
  15588. // Do not add extra process if texture lod is supported.
  15589. if (onLoad) {
  15590. onLoad(texture);
  15591. }
  15592. return;
  15593. }
  15594. var mipSlices = 3;
  15595. var gl = _this._gl;
  15596. var width = loadData.width;
  15597. if (!width) {
  15598. return;
  15599. }
  15600. var textures = [];
  15601. for (var i = 0; i < mipSlices; i++) {
  15602. //compute LOD from even spacing in smoothness (matching shader calculation)
  15603. var smoothness = i / (mipSlices - 1);
  15604. var roughness = 1 - smoothness;
  15605. var minLODIndex = lodOffset; // roughness = 0
  15606. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15607. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15608. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15609. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15610. glTextureFromLod.isCube = true;
  15611. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15616. if (loadData.isDDS) {
  15617. var info = loadData.info;
  15618. var data = loadData.data;
  15619. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15620. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15621. }
  15622. else {
  15623. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15624. }
  15625. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15626. // Wrap in a base texture for easy binding.
  15627. var lodTexture = new BABYLON.BaseTexture(scene);
  15628. lodTexture.isCube = true;
  15629. lodTexture._texture = glTextureFromLod;
  15630. glTextureFromLod.isReady = true;
  15631. textures.push(lodTexture);
  15632. }
  15633. texture._lodTextureHigh = textures[2];
  15634. texture._lodTextureMid = textures[1];
  15635. texture._lodTextureLow = textures[0];
  15636. if (onLoad) {
  15637. onLoad(texture);
  15638. }
  15639. };
  15640. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15641. };
  15642. /**
  15643. * Creates a cube texture
  15644. * @param rootUrl defines the url where the files to load is located
  15645. * @param scene defines the current scene
  15646. * @param files defines the list of files to load (1 per face)
  15647. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15648. * @param onLoad defines an optional callback raised when the texture is loaded
  15649. * @param onError defines an optional callback raised if there is an issue to load the texture
  15650. * @param format defines the format of the data
  15651. * @param forcedExtension defines the extension to use to pick the right loader
  15652. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15653. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15654. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15655. * @returns the cube texture as an InternalTexture
  15656. */
  15657. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15658. var _this = this;
  15659. if (onLoad === void 0) { onLoad = null; }
  15660. if (onError === void 0) { onError = null; }
  15661. if (forcedExtension === void 0) { forcedExtension = null; }
  15662. if (createPolynomials === void 0) { createPolynomials = false; }
  15663. if (lodScale === void 0) { lodScale = 0; }
  15664. if (lodOffset === void 0) { lodOffset = 0; }
  15665. var gl = this._gl;
  15666. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15667. texture.isCube = true;
  15668. texture.url = rootUrl;
  15669. texture.generateMipMaps = !noMipmap;
  15670. texture._lodGenerationScale = lodScale;
  15671. texture._lodGenerationOffset = lodOffset;
  15672. if (!this._doNotHandleContextLost) {
  15673. texture._extension = forcedExtension;
  15674. texture._files = files;
  15675. }
  15676. var isKTX = false;
  15677. var isDDS = false;
  15678. var isEnv = false;
  15679. var lastDot = rootUrl.lastIndexOf('.');
  15680. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15681. if (this._textureFormatInUse) {
  15682. extension = this._textureFormatInUse;
  15683. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15684. isKTX = true;
  15685. }
  15686. else {
  15687. isDDS = (extension === ".dds");
  15688. isEnv = (extension === ".env");
  15689. }
  15690. var onerror = function (request, exception) {
  15691. if (onError && request) {
  15692. onError(request.status + " " + request.statusText, exception);
  15693. }
  15694. };
  15695. if (isKTX) {
  15696. this._loadFile(rootUrl, function (data) {
  15697. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15698. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15699. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15700. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15701. ktx.uploadLevels(_this._gl, !noMipmap);
  15702. _this.setCubeMapTextureParams(gl, loadMipmap);
  15703. texture.width = ktx.pixelWidth;
  15704. texture.height = ktx.pixelHeight;
  15705. texture.isReady = true;
  15706. }, undefined, undefined, true, onerror);
  15707. }
  15708. else if (isEnv) {
  15709. this._loadFile(rootUrl, function (data) {
  15710. data = data;
  15711. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15712. if (info) {
  15713. texture.width = info.width;
  15714. texture.height = info.width;
  15715. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15716. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15717. texture.isReady = true;
  15718. if (onLoad) {
  15719. onLoad();
  15720. }
  15721. });
  15722. }
  15723. else if (onError) {
  15724. onError("Can not parse the environment file", null);
  15725. }
  15726. }, undefined, undefined, true, onerror);
  15727. }
  15728. else if (isDDS) {
  15729. if (files && files.length === 6) {
  15730. this._cascadeLoadFiles(scene, function (imgs) {
  15731. var info;
  15732. var loadMipmap = false;
  15733. var width = 0;
  15734. for (var index = 0; index < imgs.length; index++) {
  15735. var data = imgs[index];
  15736. info = BABYLON.DDSTools.GetDDSInfo(data);
  15737. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15738. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15739. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15740. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15741. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15742. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15743. }
  15744. texture.width = info.width;
  15745. texture.height = info.height;
  15746. texture.type = info.textureType;
  15747. width = info.width;
  15748. }
  15749. _this.setCubeMapTextureParams(gl, loadMipmap);
  15750. texture.isReady = true;
  15751. if (onLoad) {
  15752. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15753. }
  15754. }, files, onError);
  15755. }
  15756. else {
  15757. this._loadFile(rootUrl, function (data) {
  15758. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15759. if (createPolynomials) {
  15760. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15761. }
  15762. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15763. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15764. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15765. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15766. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15767. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15768. }
  15769. _this.setCubeMapTextureParams(gl, loadMipmap);
  15770. texture.width = info.width;
  15771. texture.height = info.height;
  15772. texture.isReady = true;
  15773. texture.type = info.textureType;
  15774. if (onLoad) {
  15775. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15776. }
  15777. }, undefined, undefined, true, onerror);
  15778. }
  15779. }
  15780. else {
  15781. if (!files) {
  15782. throw new Error("Cannot load cubemap because files were not defined");
  15783. }
  15784. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15785. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15786. var height = width;
  15787. _this._prepareWorkingCanvas();
  15788. if (!_this._workingCanvas || !_this._workingContext) {
  15789. return;
  15790. }
  15791. _this._workingCanvas.width = width;
  15792. _this._workingCanvas.height = height;
  15793. var faces = [
  15794. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15795. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15796. ];
  15797. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15798. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15799. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15800. for (var index = 0; index < faces.length; index++) {
  15801. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15802. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15803. }
  15804. if (!noMipmap) {
  15805. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15806. }
  15807. _this.setCubeMapTextureParams(gl, !noMipmap);
  15808. texture.width = width;
  15809. texture.height = height;
  15810. texture.isReady = true;
  15811. if (format) {
  15812. texture.format = format;
  15813. }
  15814. texture.onLoadedObservable.notifyObservers(texture);
  15815. texture.onLoadedObservable.clear();
  15816. if (onLoad) {
  15817. onLoad();
  15818. }
  15819. }, files, onError);
  15820. }
  15821. this._internalTexturesCache.push(texture);
  15822. return texture;
  15823. };
  15824. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15829. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15830. // this.resetTextureCache();
  15831. };
  15832. /**
  15833. * Update a raw cube texture
  15834. * @param texture defines the texture to udpdate
  15835. * @param data defines the data to store
  15836. * @param format defines the data format
  15837. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15838. * @param invertY defines if data must be stored with Y axis inverted
  15839. * @param compression defines the compression used (null by default)
  15840. * @param level defines which level of the texture to update
  15841. */
  15842. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15843. if (compression === void 0) { compression = null; }
  15844. if (level === void 0) { level = 0; }
  15845. texture._bufferViewArray = data;
  15846. texture.format = format;
  15847. texture.type = type;
  15848. texture.invertY = invertY;
  15849. texture._compression = compression;
  15850. var gl = this._gl;
  15851. var textureType = this._getWebGLTextureType(type);
  15852. var internalFormat = this._getInternalFormat(format);
  15853. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15854. var needConversion = false;
  15855. if (internalFormat === gl.RGB) {
  15856. internalFormat = gl.RGBA;
  15857. needConversion = true;
  15858. }
  15859. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15860. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15861. if (texture.width % 4 !== 0) {
  15862. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15863. }
  15864. // Data are known to be in +X +Y +Z -X -Y -Z
  15865. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15866. var faceData = data[faceIndex];
  15867. if (compression) {
  15868. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15869. }
  15870. else {
  15871. if (needConversion) {
  15872. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15873. }
  15874. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15875. }
  15876. }
  15877. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15878. if (isPot && texture.generateMipMaps && level === 0) {
  15879. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15880. }
  15881. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15882. // this.resetTextureCache();
  15883. texture.isReady = true;
  15884. };
  15885. /**
  15886. * Creates a new raw cube texture
  15887. * @param data defines the array of data to use to create each face
  15888. * @param size defines the size of the textures
  15889. * @param format defines the format of the data
  15890. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15891. * @param generateMipMaps defines if the engine should generate the mip levels
  15892. * @param invertY defines if data must be stored with Y axis inverted
  15893. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15894. * @param compression defines the compression used (null by default)
  15895. * @returns the cube texture as an InternalTexture
  15896. */
  15897. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15898. if (compression === void 0) { compression = null; }
  15899. var gl = this._gl;
  15900. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15901. texture.isCube = true;
  15902. texture.generateMipMaps = generateMipMaps;
  15903. texture.format = format;
  15904. texture.type = type;
  15905. if (!this._doNotHandleContextLost) {
  15906. texture._bufferViewArray = data;
  15907. }
  15908. var textureType = this._getWebGLTextureType(type);
  15909. var internalFormat = this._getInternalFormat(format);
  15910. if (internalFormat === gl.RGB) {
  15911. internalFormat = gl.RGBA;
  15912. }
  15913. var width = size;
  15914. var height = width;
  15915. texture.width = width;
  15916. texture.height = height;
  15917. // Double check on POT to generate Mips.
  15918. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15919. if (!isPot) {
  15920. generateMipMaps = false;
  15921. }
  15922. // Upload data if needed. The texture won't be ready until then.
  15923. if (data) {
  15924. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15925. }
  15926. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15927. // Filters
  15928. if (data && generateMipMaps) {
  15929. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15930. }
  15931. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15934. }
  15935. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15938. }
  15939. else {
  15940. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15943. }
  15944. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15945. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15946. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15947. return texture;
  15948. };
  15949. /**
  15950. * Creates a new raw cube texture from a specified url
  15951. * @param url defines the url where the data is located
  15952. * @param scene defines the current scene
  15953. * @param size defines the size of the textures
  15954. * @param format defines the format of the data
  15955. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15956. * @param noMipmap defines if the engine should avoid generating the mip levels
  15957. * @param callback defines a callback used to extract texture data from loaded data
  15958. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15959. * @param onLoad defines a callback called when texture is loaded
  15960. * @param onError defines a callback called if there is an error
  15961. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15962. * @param invertY defines if data must be stored with Y axis inverted
  15963. * @returns the cube texture as an InternalTexture
  15964. */
  15965. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15966. var _this = this;
  15967. if (onLoad === void 0) { onLoad = null; }
  15968. if (onError === void 0) { onError = null; }
  15969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15970. if (invertY === void 0) { invertY = false; }
  15971. var gl = this._gl;
  15972. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15973. scene._addPendingData(texture);
  15974. texture.url = url;
  15975. this._internalTexturesCache.push(texture);
  15976. var onerror = function (request, exception) {
  15977. scene._removePendingData(texture);
  15978. if (onError && request) {
  15979. onError(request.status + " " + request.statusText, exception);
  15980. }
  15981. };
  15982. var internalCallback = function (data) {
  15983. var width = texture.width;
  15984. var faceDataArrays = callback(data);
  15985. if (!faceDataArrays) {
  15986. return;
  15987. }
  15988. if (mipmapGenerator) {
  15989. var textureType = _this._getWebGLTextureType(type);
  15990. var internalFormat = _this._getInternalFormat(format);
  15991. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15992. var needConversion = false;
  15993. if (internalFormat === gl.RGB) {
  15994. internalFormat = gl.RGBA;
  15995. needConversion = true;
  15996. }
  15997. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15998. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15999. var mipData = mipmapGenerator(faceDataArrays);
  16000. for (var level = 0; level < mipData.length; level++) {
  16001. var mipSize = width >> level;
  16002. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16003. var mipFaceData = mipData[level][faceIndex];
  16004. if (needConversion) {
  16005. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16006. }
  16007. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16008. }
  16009. }
  16010. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16011. }
  16012. else {
  16013. texture.generateMipMaps = !noMipmap;
  16014. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16015. }
  16016. texture.isReady = true;
  16017. // this.resetTextureCache();
  16018. scene._removePendingData(texture);
  16019. if (onLoad) {
  16020. onLoad();
  16021. }
  16022. };
  16023. this._loadFile(url, function (data) {
  16024. internalCallback(data);
  16025. }, undefined, scene.database, true, onerror);
  16026. return texture;
  16027. };
  16028. ;
  16029. /**
  16030. * Update a raw 3D texture
  16031. * @param texture defines the texture to update
  16032. * @param data defines the data to store
  16033. * @param format defines the data format
  16034. * @param invertY defines if data must be stored with Y axis inverted
  16035. * @param compression defines the used compression (can be null)
  16036. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16037. */
  16038. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16039. if (compression === void 0) { compression = null; }
  16040. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16041. var internalType = this._getWebGLTextureType(textureType);
  16042. var internalFormat = this._getInternalFormat(format);
  16043. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16044. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16045. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16046. if (!this._doNotHandleContextLost) {
  16047. texture._bufferView = data;
  16048. texture.format = format;
  16049. texture.invertY = invertY;
  16050. texture._compression = compression;
  16051. }
  16052. if (texture.width % 4 !== 0) {
  16053. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16054. }
  16055. if (compression && data) {
  16056. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16057. }
  16058. else {
  16059. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16060. }
  16061. if (texture.generateMipMaps) {
  16062. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16063. }
  16064. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16065. // this.resetTextureCache();
  16066. texture.isReady = true;
  16067. };
  16068. /**
  16069. * Creates a new raw 3D texture
  16070. * @param data defines the data used to create the texture
  16071. * @param width defines the width of the texture
  16072. * @param height defines the height of the texture
  16073. * @param depth defines the depth of the texture
  16074. * @param format defines the format of the texture
  16075. * @param generateMipMaps defines if the engine must generate mip levels
  16076. * @param invertY defines if data must be stored with Y axis inverted
  16077. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16078. * @param compression defines the compressed used (can be null)
  16079. * @param textureType defines the compressed used (can be null)
  16080. * @returns a new raw 3D texture (stored in an InternalTexture)
  16081. */
  16082. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16083. if (compression === void 0) { compression = null; }
  16084. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16085. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16086. texture.baseWidth = width;
  16087. texture.baseHeight = height;
  16088. texture.baseDepth = depth;
  16089. texture.width = width;
  16090. texture.height = height;
  16091. texture.depth = depth;
  16092. texture.format = format;
  16093. texture.type = textureType;
  16094. texture.generateMipMaps = generateMipMaps;
  16095. texture.samplingMode = samplingMode;
  16096. texture.is3D = true;
  16097. if (!this._doNotHandleContextLost) {
  16098. texture._bufferView = data;
  16099. }
  16100. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16101. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16102. // Filters
  16103. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16104. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16105. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16106. if (generateMipMaps) {
  16107. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16108. }
  16109. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16110. this._internalTexturesCache.push(texture);
  16111. return texture;
  16112. };
  16113. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16114. var gl = this._gl;
  16115. if (!gl) {
  16116. return;
  16117. }
  16118. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16119. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16121. if (!noMipmap && !isCompressed) {
  16122. gl.generateMipmap(gl.TEXTURE_2D);
  16123. }
  16124. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16125. // this.resetTextureCache();
  16126. if (scene) {
  16127. scene._removePendingData(texture);
  16128. }
  16129. texture.onLoadedObservable.notifyObservers(texture);
  16130. texture.onLoadedObservable.clear();
  16131. };
  16132. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16133. var _this = this;
  16134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16135. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16136. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16137. var gl = this._gl;
  16138. if (!gl) {
  16139. return;
  16140. }
  16141. if (!texture._webGLTexture) {
  16142. // this.resetTextureCache();
  16143. if (scene) {
  16144. scene._removePendingData(texture);
  16145. }
  16146. return;
  16147. }
  16148. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16149. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16150. texture.baseWidth = width;
  16151. texture.baseHeight = height;
  16152. texture.width = potWidth;
  16153. texture.height = potHeight;
  16154. texture.isReady = true;
  16155. if (processFunction(potWidth, potHeight, function () {
  16156. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16157. })) {
  16158. // Returning as texture needs extra async steps
  16159. return;
  16160. }
  16161. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16162. };
  16163. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16164. // Create new RGBA data container.
  16165. var rgbaData;
  16166. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16167. rgbaData = new Float32Array(width * height * 4);
  16168. }
  16169. else {
  16170. rgbaData = new Uint32Array(width * height * 4);
  16171. }
  16172. // Convert each pixel.
  16173. for (var x = 0; x < width; x++) {
  16174. for (var y = 0; y < height; y++) {
  16175. var index = (y * width + x) * 3;
  16176. var newIndex = (y * width + x) * 4;
  16177. // Map Old Value to new value.
  16178. rgbaData[newIndex + 0] = rgbData[index + 0];
  16179. rgbaData[newIndex + 1] = rgbData[index + 1];
  16180. rgbaData[newIndex + 2] = rgbData[index + 2];
  16181. // Add fully opaque alpha channel.
  16182. rgbaData[newIndex + 3] = 1;
  16183. }
  16184. }
  16185. return rgbaData;
  16186. };
  16187. /** @hidden */
  16188. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16189. var gl = this._gl;
  16190. if (texture._framebuffer) {
  16191. gl.deleteFramebuffer(texture._framebuffer);
  16192. texture._framebuffer = null;
  16193. }
  16194. if (texture._depthStencilBuffer) {
  16195. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16196. texture._depthStencilBuffer = null;
  16197. }
  16198. if (texture._MSAAFramebuffer) {
  16199. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16200. texture._MSAAFramebuffer = null;
  16201. }
  16202. if (texture._MSAARenderBuffer) {
  16203. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16204. texture._MSAARenderBuffer = null;
  16205. }
  16206. };
  16207. /** @hidden */
  16208. Engine.prototype._releaseTexture = function (texture) {
  16209. var gl = this._gl;
  16210. this._releaseFramebufferObjects(texture);
  16211. gl.deleteTexture(texture._webGLTexture);
  16212. // Unbind channels
  16213. this.unbindAllTextures();
  16214. var index = this._internalTexturesCache.indexOf(texture);
  16215. if (index !== -1) {
  16216. this._internalTexturesCache.splice(index, 1);
  16217. }
  16218. // Integrated fixed lod samplers.
  16219. if (texture._lodTextureHigh) {
  16220. texture._lodTextureHigh.dispose();
  16221. }
  16222. if (texture._lodTextureMid) {
  16223. texture._lodTextureMid.dispose();
  16224. }
  16225. if (texture._lodTextureLow) {
  16226. texture._lodTextureLow.dispose();
  16227. }
  16228. // Set output texture of post process to null if the texture has been released/disposed
  16229. this.scenes.forEach(function (scene) {
  16230. scene.postProcesses.forEach(function (postProcess) {
  16231. if (postProcess._outputTexture == texture) {
  16232. postProcess._outputTexture = null;
  16233. }
  16234. });
  16235. scene.cameras.forEach(function (camera) {
  16236. camera._postProcesses.forEach(function (postProcess) {
  16237. if (postProcess) {
  16238. if (postProcess._outputTexture == texture) {
  16239. postProcess._outputTexture = null;
  16240. }
  16241. }
  16242. });
  16243. });
  16244. });
  16245. };
  16246. Engine.prototype.setProgram = function (program) {
  16247. if (this._currentProgram !== program) {
  16248. this._gl.useProgram(program);
  16249. this._currentProgram = program;
  16250. }
  16251. };
  16252. /**
  16253. * Binds an effect to the webGL context
  16254. * @param effect defines the effect to bind
  16255. */
  16256. Engine.prototype.bindSamplers = function (effect) {
  16257. this.setProgram(effect.getProgram());
  16258. var samplers = effect.getSamplers();
  16259. for (var index = 0; index < samplers.length; index++) {
  16260. var uniform = effect.getUniform(samplers[index]);
  16261. if (uniform) {
  16262. this._boundUniforms[index] = uniform;
  16263. }
  16264. }
  16265. this._currentEffect = null;
  16266. };
  16267. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16268. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16269. return;
  16270. }
  16271. // Remove
  16272. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16273. // Bind last to it
  16274. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16275. // Bind to dummy
  16276. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16277. };
  16278. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16279. if (!internalTexture) {
  16280. return -1;
  16281. }
  16282. internalTexture._initialSlot = channel;
  16283. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16284. if (channel !== internalTexture._designatedSlot) {
  16285. this._textureCollisions.addCount(1, false);
  16286. }
  16287. }
  16288. else {
  16289. if (channel !== internalTexture._designatedSlot) {
  16290. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16291. return internalTexture._designatedSlot;
  16292. }
  16293. else {
  16294. // No slot for this texture, let's pick a new one (if we find a free slot)
  16295. if (this._nextFreeTextureSlots.length) {
  16296. return this._nextFreeTextureSlots[0];
  16297. }
  16298. // We need to recycle the oldest bound texture, sorry.
  16299. this._textureCollisions.addCount(1, false);
  16300. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16301. }
  16302. }
  16303. }
  16304. return channel;
  16305. };
  16306. Engine.prototype._linkTrackers = function (previous, next) {
  16307. previous.next = next;
  16308. next.previous = previous;
  16309. };
  16310. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16311. var currentSlot = internalTexture._designatedSlot;
  16312. if (currentSlot === -1) {
  16313. return -1;
  16314. }
  16315. internalTexture._designatedSlot = -1;
  16316. if (this.disableTextureBindingOptimization) {
  16317. return -1;
  16318. }
  16319. // Remove from bound list
  16320. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16321. // Free the slot
  16322. this._boundTexturesCache[currentSlot] = null;
  16323. this._nextFreeTextureSlots.push(currentSlot);
  16324. return currentSlot;
  16325. };
  16326. Engine.prototype._activateCurrentTexture = function () {
  16327. if (this._currentTextureChannel !== this._activeChannel) {
  16328. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16329. this._currentTextureChannel = this._activeChannel;
  16330. }
  16331. };
  16332. /** @hidden */
  16333. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16334. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16335. if (force === void 0) { force = false; }
  16336. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16337. this._activeChannel = texture._designatedSlot;
  16338. }
  16339. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16340. var isTextureForRendering = texture && texture._initialSlot > -1;
  16341. if (currentTextureBound !== texture || force) {
  16342. if (currentTextureBound) {
  16343. this._removeDesignatedSlot(currentTextureBound);
  16344. }
  16345. this._activateCurrentTexture();
  16346. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16347. this._boundTexturesCache[this._activeChannel] = texture;
  16348. if (texture) {
  16349. if (!this.disableTextureBindingOptimization) {
  16350. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16351. if (slotIndex > -1) {
  16352. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16353. }
  16354. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16355. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16356. }
  16357. texture._designatedSlot = this._activeChannel;
  16358. }
  16359. }
  16360. else if (forTextureDataUpdate) {
  16361. this._activateCurrentTexture();
  16362. }
  16363. if (isTextureForRendering && !forTextureDataUpdate) {
  16364. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16365. }
  16366. };
  16367. /** @hidden */
  16368. Engine.prototype._bindTexture = function (channel, texture) {
  16369. if (channel < 0) {
  16370. return;
  16371. }
  16372. if (texture) {
  16373. channel = this._getCorrectTextureChannel(channel, texture);
  16374. }
  16375. this._activeChannel = channel;
  16376. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16377. };
  16378. /**
  16379. * Sets a texture to the webGL context from a postprocess
  16380. * @param channel defines the channel to use
  16381. * @param postProcess defines the source postprocess
  16382. */
  16383. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16384. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16385. };
  16386. /**
  16387. * Binds the output of the passed in post process to the texture channel specified
  16388. * @param channel The channel the texture should be bound to
  16389. * @param postProcess The post process which's output should be bound
  16390. */
  16391. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16392. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16393. };
  16394. /**
  16395. * Unbind all textures from the webGL context
  16396. */
  16397. Engine.prototype.unbindAllTextures = function () {
  16398. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16399. this._activeChannel = channel;
  16400. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16401. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16402. if (this.webGLVersion > 1) {
  16403. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16404. }
  16405. }
  16406. };
  16407. /**
  16408. * Sets a texture to the according uniform.
  16409. * @param channel The texture channel
  16410. * @param uniform The uniform to set
  16411. * @param texture The texture to apply
  16412. */
  16413. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16414. if (channel < 0) {
  16415. return;
  16416. }
  16417. if (uniform) {
  16418. this._boundUniforms[channel] = uniform;
  16419. }
  16420. this._setTexture(channel, texture);
  16421. };
  16422. /**
  16423. * Sets a depth stencil texture from a render target to the according uniform.
  16424. * @param channel The texture channel
  16425. * @param uniform The uniform to set
  16426. * @param texture The render target texture containing the depth stencil texture to apply
  16427. */
  16428. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16429. if (channel < 0) {
  16430. return;
  16431. }
  16432. if (uniform) {
  16433. this._boundUniforms[channel] = uniform;
  16434. }
  16435. if (!texture || !texture.depthStencilTexture) {
  16436. this._setTexture(channel, null);
  16437. }
  16438. else {
  16439. this._setTexture(channel, texture, false, true);
  16440. }
  16441. };
  16442. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16443. var uniform = this._boundUniforms[sourceSlot];
  16444. if (uniform._currentState === destination) {
  16445. return;
  16446. }
  16447. this._gl.uniform1i(uniform, destination);
  16448. uniform._currentState = destination;
  16449. };
  16450. Engine.prototype._getTextureWrapMode = function (mode) {
  16451. switch (mode) {
  16452. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16453. return this._gl.REPEAT;
  16454. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16455. return this._gl.CLAMP_TO_EDGE;
  16456. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16457. return this._gl.MIRRORED_REPEAT;
  16458. }
  16459. return this._gl.REPEAT;
  16460. };
  16461. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16462. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16463. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16464. // Not ready?
  16465. if (!texture) {
  16466. if (this._boundTexturesCache[channel] != null) {
  16467. this._activeChannel = channel;
  16468. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16469. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16470. if (this.webGLVersion > 1) {
  16471. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16472. }
  16473. }
  16474. return false;
  16475. }
  16476. // Video
  16477. if (texture.video) {
  16478. this._activeChannel = channel;
  16479. texture.update();
  16480. }
  16481. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16482. texture.delayLoad();
  16483. return false;
  16484. }
  16485. var internalTexture;
  16486. if (depthStencilTexture) {
  16487. internalTexture = texture.depthStencilTexture;
  16488. }
  16489. else if (texture.isReady()) {
  16490. internalTexture = texture.getInternalTexture();
  16491. }
  16492. else if (texture.isCube) {
  16493. internalTexture = this.emptyCubeTexture;
  16494. }
  16495. else if (texture.is3D) {
  16496. internalTexture = this.emptyTexture3D;
  16497. }
  16498. else {
  16499. internalTexture = this.emptyTexture;
  16500. }
  16501. if (!isPartOfTextureArray) {
  16502. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16503. }
  16504. var needToBind = true;
  16505. if (this._boundTexturesCache[channel] === internalTexture) {
  16506. this._moveBoundTextureOnTop(internalTexture);
  16507. if (!isPartOfTextureArray) {
  16508. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16509. }
  16510. needToBind = false;
  16511. }
  16512. this._activeChannel = channel;
  16513. if (internalTexture && internalTexture.is3D) {
  16514. if (needToBind) {
  16515. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16516. }
  16517. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16518. internalTexture._cachedWrapU = texture.wrapU;
  16519. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16520. }
  16521. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16522. internalTexture._cachedWrapV = texture.wrapV;
  16523. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16524. }
  16525. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16526. internalTexture._cachedWrapR = texture.wrapR;
  16527. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16528. }
  16529. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16530. }
  16531. else if (internalTexture && internalTexture.isCube) {
  16532. if (needToBind) {
  16533. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16534. }
  16535. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16536. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16537. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16538. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16539. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16540. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16541. }
  16542. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16543. }
  16544. else {
  16545. if (needToBind) {
  16546. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16547. }
  16548. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16549. internalTexture._cachedWrapU = texture.wrapU;
  16550. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16551. }
  16552. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16553. internalTexture._cachedWrapV = texture.wrapV;
  16554. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16555. }
  16556. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16557. }
  16558. return true;
  16559. };
  16560. /**
  16561. * Sets an array of texture to the webGL context
  16562. * @param channel defines the channel where the texture array must be set
  16563. * @param uniform defines the associated uniform location
  16564. * @param textures defines the array of textures to bind
  16565. */
  16566. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16567. if (channel < 0 || !uniform) {
  16568. return;
  16569. }
  16570. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16571. this._textureUnits = new Int32Array(textures.length);
  16572. }
  16573. for (var i = 0; i < textures.length; i++) {
  16574. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16575. }
  16576. this._gl.uniform1iv(uniform, this._textureUnits);
  16577. for (var index = 0; index < textures.length; index++) {
  16578. this._setTexture(this._textureUnits[index], textures[index], true);
  16579. }
  16580. };
  16581. /** @hidden */
  16582. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16583. var internalTexture = texture.getInternalTexture();
  16584. if (!internalTexture) {
  16585. return;
  16586. }
  16587. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16588. var value = texture.anisotropicFilteringLevel;
  16589. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16590. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16591. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16592. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16593. }
  16594. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16595. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16596. internalTexture._cachedAnisotropicFilteringLevel = value;
  16597. }
  16598. };
  16599. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16600. this._bindTextureDirectly(target, texture, true, true);
  16601. this._gl.texParameterf(target, parameter, value);
  16602. };
  16603. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16604. if (texture) {
  16605. this._bindTextureDirectly(target, texture, true, true);
  16606. }
  16607. this._gl.texParameteri(target, parameter, value);
  16608. };
  16609. /**
  16610. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16611. * @param x defines the x coordinate of the rectangle where pixels must be read
  16612. * @param y defines the y coordinate of the rectangle where pixels must be read
  16613. * @param width defines the width of the rectangle where pixels must be read
  16614. * @param height defines the height of the rectangle where pixels must be read
  16615. * @returns a Uint8Array containing RGBA colors
  16616. */
  16617. Engine.prototype.readPixels = function (x, y, width, height) {
  16618. var data = new Uint8Array(height * width * 4);
  16619. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16620. return data;
  16621. };
  16622. /**
  16623. * Add an externaly attached data from its key.
  16624. * This method call will fail and return false, if such key already exists.
  16625. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16626. * @param key the unique key that identifies the data
  16627. * @param data the data object to associate to the key for this Engine instance
  16628. * @return true if no such key were already present and the data was added successfully, false otherwise
  16629. */
  16630. Engine.prototype.addExternalData = function (key, data) {
  16631. if (!this._externalData) {
  16632. this._externalData = new BABYLON.StringDictionary();
  16633. }
  16634. return this._externalData.add(key, data);
  16635. };
  16636. /**
  16637. * Get an externaly attached data from its key
  16638. * @param key the unique key that identifies the data
  16639. * @return the associated data, if present (can be null), or undefined if not present
  16640. */
  16641. Engine.prototype.getExternalData = function (key) {
  16642. if (!this._externalData) {
  16643. this._externalData = new BABYLON.StringDictionary();
  16644. }
  16645. return this._externalData.get(key);
  16646. };
  16647. /**
  16648. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16649. * @param key the unique key that identifies the data
  16650. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16651. * @return the associated data, can be null if the factory returned null.
  16652. */
  16653. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16654. if (!this._externalData) {
  16655. this._externalData = new BABYLON.StringDictionary();
  16656. }
  16657. return this._externalData.getOrAddWithFactory(key, factory);
  16658. };
  16659. /**
  16660. * Remove an externaly attached data from the Engine instance
  16661. * @param key the unique key that identifies the data
  16662. * @return true if the data was successfully removed, false if it doesn't exist
  16663. */
  16664. Engine.prototype.removeExternalData = function (key) {
  16665. if (!this._externalData) {
  16666. this._externalData = new BABYLON.StringDictionary();
  16667. }
  16668. return this._externalData.remove(key);
  16669. };
  16670. /**
  16671. * Unbind all vertex attributes from the webGL context
  16672. */
  16673. Engine.prototype.unbindAllAttributes = function () {
  16674. if (this._mustWipeVertexAttributes) {
  16675. this._mustWipeVertexAttributes = false;
  16676. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16677. this._gl.disableVertexAttribArray(i);
  16678. this._vertexAttribArraysEnabled[i] = false;
  16679. this._currentBufferPointers[i].active = false;
  16680. }
  16681. return;
  16682. }
  16683. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16684. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16685. continue;
  16686. }
  16687. this._gl.disableVertexAttribArray(i);
  16688. this._vertexAttribArraysEnabled[i] = false;
  16689. this._currentBufferPointers[i].active = false;
  16690. }
  16691. };
  16692. /**
  16693. * 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
  16694. */
  16695. Engine.prototype.releaseEffects = function () {
  16696. for (var name in this._compiledEffects) {
  16697. this._deleteProgram(this._compiledEffects[name]._program);
  16698. }
  16699. this._compiledEffects = {};
  16700. };
  16701. /**
  16702. * Dispose and release all associated resources
  16703. */
  16704. Engine.prototype.dispose = function () {
  16705. this.hideLoadingUI();
  16706. this.stopRenderLoop();
  16707. // Release postProcesses
  16708. while (this.postProcesses.length) {
  16709. this.postProcesses[0].dispose();
  16710. }
  16711. // Empty texture
  16712. if (this._emptyTexture) {
  16713. this._releaseTexture(this._emptyTexture);
  16714. this._emptyTexture = null;
  16715. }
  16716. if (this._emptyCubeTexture) {
  16717. this._releaseTexture(this._emptyCubeTexture);
  16718. this._emptyCubeTexture = null;
  16719. }
  16720. // Rescale PP
  16721. if (this._rescalePostProcess) {
  16722. this._rescalePostProcess.dispose();
  16723. }
  16724. // Release scenes
  16725. while (this.scenes.length) {
  16726. this.scenes[0].dispose();
  16727. }
  16728. // Release audio engine
  16729. if (Engine.audioEngine) {
  16730. Engine.audioEngine.dispose();
  16731. }
  16732. // Release effects
  16733. this.releaseEffects();
  16734. // Unbind
  16735. this.unbindAllAttributes();
  16736. this._boundUniforms = [];
  16737. if (this._dummyFramebuffer) {
  16738. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16739. }
  16740. //WebVR
  16741. this.disableVR();
  16742. // Events
  16743. if (BABYLON.Tools.IsWindowObjectExist()) {
  16744. window.removeEventListener("blur", this._onBlur);
  16745. window.removeEventListener("focus", this._onFocus);
  16746. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16747. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16748. if (this._renderingCanvas) {
  16749. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16750. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16751. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16752. if (!this._doNotHandleContextLost) {
  16753. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16754. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16755. }
  16756. }
  16757. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16758. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16759. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16760. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16761. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16762. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16763. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16764. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16765. if (this._onVrDisplayConnect) {
  16766. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16767. if (this._onVrDisplayDisconnect) {
  16768. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16769. }
  16770. if (this._onVrDisplayPresentChange) {
  16771. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16772. }
  16773. this._onVrDisplayConnect = null;
  16774. this._onVrDisplayDisconnect = null;
  16775. }
  16776. }
  16777. // Remove from Instances
  16778. var index = Engine.Instances.indexOf(this);
  16779. if (index >= 0) {
  16780. Engine.Instances.splice(index, 1);
  16781. }
  16782. this._workingCanvas = null;
  16783. this._workingContext = null;
  16784. this._currentBufferPointers = [];
  16785. this._renderingCanvas = null;
  16786. this._currentProgram = null;
  16787. this._bindedRenderFunction = null;
  16788. this.onResizeObservable.clear();
  16789. this.onCanvasBlurObservable.clear();
  16790. this.onCanvasFocusObservable.clear();
  16791. this.onCanvasPointerOutObservable.clear();
  16792. this.onBeginFrameObservable.clear();
  16793. this.onEndFrameObservable.clear();
  16794. BABYLON.Effect.ResetCache();
  16795. // Abort active requests
  16796. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16797. var request = _a[_i];
  16798. request.abort();
  16799. }
  16800. };
  16801. // Loading screen
  16802. /**
  16803. * Display the loading screen
  16804. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16805. */
  16806. Engine.prototype.displayLoadingUI = function () {
  16807. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16808. return;
  16809. }
  16810. var loadingScreen = this.loadingScreen;
  16811. if (loadingScreen) {
  16812. loadingScreen.displayLoadingUI();
  16813. }
  16814. };
  16815. /**
  16816. * Hide the loading screen
  16817. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16818. */
  16819. Engine.prototype.hideLoadingUI = function () {
  16820. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16821. return;
  16822. }
  16823. var loadingScreen = this.loadingScreen;
  16824. if (loadingScreen) {
  16825. loadingScreen.hideLoadingUI();
  16826. }
  16827. };
  16828. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16829. /**
  16830. * Gets the current loading screen object
  16831. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16832. */
  16833. get: function () {
  16834. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16835. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16836. return this._loadingScreen;
  16837. },
  16838. /**
  16839. * Sets the current loading screen object
  16840. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16841. */
  16842. set: function (loadingScreen) {
  16843. this._loadingScreen = loadingScreen;
  16844. },
  16845. enumerable: true,
  16846. configurable: true
  16847. });
  16848. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16849. /**
  16850. * Sets the current loading screen text
  16851. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16852. */
  16853. set: function (text) {
  16854. this.loadingScreen.loadingUIText = text;
  16855. },
  16856. enumerable: true,
  16857. configurable: true
  16858. });
  16859. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16860. /**
  16861. * Sets the current loading screen background color
  16862. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16863. */
  16864. set: function (color) {
  16865. this.loadingScreen.loadingUIBackgroundColor = color;
  16866. },
  16867. enumerable: true,
  16868. configurable: true
  16869. });
  16870. /**
  16871. * Attach a new callback raised when context lost event is fired
  16872. * @param callback defines the callback to call
  16873. */
  16874. Engine.prototype.attachContextLostEvent = function (callback) {
  16875. if (this._renderingCanvas) {
  16876. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16877. }
  16878. };
  16879. /**
  16880. * Attach a new callback raised when context restored event is fired
  16881. * @param callback defines the callback to call
  16882. */
  16883. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16884. if (this._renderingCanvas) {
  16885. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16886. }
  16887. };
  16888. /**
  16889. * Gets the source code of the vertex shader associated with a specific webGL program
  16890. * @param program defines the program to use
  16891. * @returns a string containing the source code of the vertex shader associated with the program
  16892. */
  16893. Engine.prototype.getVertexShaderSource = function (program) {
  16894. var shaders = this._gl.getAttachedShaders(program);
  16895. if (!shaders) {
  16896. return null;
  16897. }
  16898. return this._gl.getShaderSource(shaders[0]);
  16899. };
  16900. /**
  16901. * Gets the source code of the fragment shader associated with a specific webGL program
  16902. * @param program defines the program to use
  16903. * @returns a string containing the source code of the fragment shader associated with the program
  16904. */
  16905. Engine.prototype.getFragmentShaderSource = function (program) {
  16906. var shaders = this._gl.getAttachedShaders(program);
  16907. if (!shaders) {
  16908. return null;
  16909. }
  16910. return this._gl.getShaderSource(shaders[1]);
  16911. };
  16912. /**
  16913. * Get the current error code of the webGL context
  16914. * @returns the error code
  16915. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16916. */
  16917. Engine.prototype.getError = function () {
  16918. return this._gl.getError();
  16919. };
  16920. // FPS
  16921. /**
  16922. * Gets the current framerate
  16923. * @returns a number representing the framerate
  16924. */
  16925. Engine.prototype.getFps = function () {
  16926. return this._fps;
  16927. };
  16928. /**
  16929. * Gets the time spent between current and previous frame
  16930. * @returns a number representing the delta time in ms
  16931. */
  16932. Engine.prototype.getDeltaTime = function () {
  16933. return this._deltaTime;
  16934. };
  16935. Engine.prototype._measureFps = function () {
  16936. this._performanceMonitor.sampleFrame();
  16937. this._fps = this._performanceMonitor.averageFPS;
  16938. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16939. };
  16940. /** @hidden */
  16941. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16942. if (faceIndex === void 0) { faceIndex = -1; }
  16943. if (level === void 0) { level = 0; }
  16944. var gl = this._gl;
  16945. if (!this._dummyFramebuffer) {
  16946. var dummy = gl.createFramebuffer();
  16947. if (!dummy) {
  16948. throw new Error("Unable to create dummy framebuffer");
  16949. }
  16950. this._dummyFramebuffer = dummy;
  16951. }
  16952. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16953. if (faceIndex > -1) {
  16954. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16955. }
  16956. else {
  16957. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16958. }
  16959. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16960. var buffer;
  16961. switch (readType) {
  16962. case gl.UNSIGNED_BYTE:
  16963. buffer = new Uint8Array(4 * width * height);
  16964. readType = gl.UNSIGNED_BYTE;
  16965. break;
  16966. default:
  16967. buffer = new Float32Array(4 * width * height);
  16968. readType = gl.FLOAT;
  16969. break;
  16970. }
  16971. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16972. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16973. return buffer;
  16974. };
  16975. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16976. if (this._webGLVersion > 1) {
  16977. return this._caps.colorBufferFloat;
  16978. }
  16979. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16980. };
  16981. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16982. if (this._webGLVersion > 1) {
  16983. return this._caps.colorBufferFloat;
  16984. }
  16985. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16986. };
  16987. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16988. Engine.prototype._canRenderToFramebuffer = function (type) {
  16989. var gl = this._gl;
  16990. //clear existing errors
  16991. while (gl.getError() !== gl.NO_ERROR) { }
  16992. var successful = true;
  16993. var texture = gl.createTexture();
  16994. gl.bindTexture(gl.TEXTURE_2D, texture);
  16995. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16996. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16998. var fb = gl.createFramebuffer();
  16999. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17000. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17001. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17002. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17003. successful = successful && (gl.getError() === gl.NO_ERROR);
  17004. //try render by clearing frame buffer's color buffer
  17005. if (successful) {
  17006. gl.clear(gl.COLOR_BUFFER_BIT);
  17007. successful = successful && (gl.getError() === gl.NO_ERROR);
  17008. }
  17009. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17010. if (successful) {
  17011. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17012. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17013. var readFormat = gl.RGBA;
  17014. var readType = gl.UNSIGNED_BYTE;
  17015. var buffer = new Uint8Array(4);
  17016. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17017. successful = successful && (gl.getError() === gl.NO_ERROR);
  17018. }
  17019. //clean up
  17020. gl.deleteTexture(texture);
  17021. gl.deleteFramebuffer(fb);
  17022. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17023. //clear accumulated errors
  17024. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17025. return successful;
  17026. };
  17027. /** @hidden */
  17028. Engine.prototype._getWebGLTextureType = function (type) {
  17029. if (type === Engine.TEXTURETYPE_FLOAT) {
  17030. return this._gl.FLOAT;
  17031. }
  17032. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17033. // Add Half Float Constant.
  17034. return this._gl.HALF_FLOAT_OES;
  17035. }
  17036. return this._gl.UNSIGNED_BYTE;
  17037. };
  17038. ;
  17039. Engine.prototype._getInternalFormat = function (format) {
  17040. var internalFormat = this._gl.RGBA;
  17041. switch (format) {
  17042. case Engine.TEXTUREFORMAT_ALPHA:
  17043. internalFormat = this._gl.ALPHA;
  17044. break;
  17045. case Engine.TEXTUREFORMAT_LUMINANCE:
  17046. internalFormat = this._gl.LUMINANCE;
  17047. break;
  17048. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17049. internalFormat = this._gl.LUMINANCE_ALPHA;
  17050. break;
  17051. case Engine.TEXTUREFORMAT_RGB:
  17052. internalFormat = this._gl.RGB;
  17053. break;
  17054. case Engine.TEXTUREFORMAT_RGBA:
  17055. internalFormat = this._gl.RGBA;
  17056. break;
  17057. case Engine.TEXTUREFORMAT_R:
  17058. internalFormat = this._gl.RED;
  17059. break;
  17060. case Engine.TEXTUREFORMAT_RG:
  17061. internalFormat = this._gl.RG;
  17062. break;
  17063. }
  17064. return internalFormat;
  17065. };
  17066. /** @hidden */
  17067. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17068. if (this._webGLVersion === 1) {
  17069. if (format !== undefined) {
  17070. switch (format) {
  17071. case Engine.TEXTUREFORMAT_LUMINANCE:
  17072. return this._gl.LUMINANCE;
  17073. case Engine.TEXTUREFORMAT_ALPHA:
  17074. return this._gl.ALPHA;
  17075. }
  17076. }
  17077. return this._gl.RGBA;
  17078. }
  17079. if (type === Engine.TEXTURETYPE_FLOAT) {
  17080. if (format !== undefined) {
  17081. switch (format) {
  17082. case Engine.TEXTUREFORMAT_R:
  17083. return this._gl.R32F;
  17084. case Engine.TEXTUREFORMAT_RG:
  17085. return this._gl.RG32F;
  17086. case Engine.TEXTUREFORMAT_RGB:
  17087. return this._gl.RGB32F;
  17088. }
  17089. }
  17090. return this._gl.RGBA32F;
  17091. }
  17092. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17093. if (format) {
  17094. switch (format) {
  17095. case Engine.TEXTUREFORMAT_R:
  17096. return this._gl.R16F;
  17097. case Engine.TEXTUREFORMAT_RG:
  17098. return this._gl.RG16F;
  17099. case Engine.TEXTUREFORMAT_RGB:
  17100. return this._gl.RGB16F;
  17101. }
  17102. }
  17103. return this._gl.RGBA16F;
  17104. }
  17105. if (format !== undefined) {
  17106. switch (format) {
  17107. case Engine.TEXTUREFORMAT_LUMINANCE:
  17108. return this._gl.LUMINANCE;
  17109. case Engine.TEXTUREFORMAT_RGB:
  17110. return this._gl.RGB;
  17111. case Engine.TEXTUREFORMAT_R:
  17112. return this._gl.R8;
  17113. case Engine.TEXTUREFORMAT_RG:
  17114. return this._gl.RG8;
  17115. case Engine.TEXTUREFORMAT_ALPHA:
  17116. return this._gl.ALPHA;
  17117. }
  17118. }
  17119. return this._gl.RGBA;
  17120. };
  17121. ;
  17122. /** @hidden */
  17123. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17124. if (type === Engine.TEXTURETYPE_FLOAT) {
  17125. return this._gl.RGBA32F;
  17126. }
  17127. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17128. return this._gl.RGBA16F;
  17129. }
  17130. return this._gl.RGBA8;
  17131. };
  17132. ;
  17133. /**
  17134. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17135. * @return the new query
  17136. */
  17137. Engine.prototype.createQuery = function () {
  17138. return this._gl.createQuery();
  17139. };
  17140. /**
  17141. * Delete and release a webGL query
  17142. * @param query defines the query to delete
  17143. * @return the current engine
  17144. */
  17145. Engine.prototype.deleteQuery = function (query) {
  17146. this._gl.deleteQuery(query);
  17147. return this;
  17148. };
  17149. /**
  17150. * Check if a given query has resolved and got its value
  17151. * @param query defines the query to check
  17152. * @returns true if the query got its value
  17153. */
  17154. Engine.prototype.isQueryResultAvailable = function (query) {
  17155. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17156. };
  17157. /**
  17158. * Gets the value of a given query
  17159. * @param query defines the query to check
  17160. * @returns the value of the query
  17161. */
  17162. Engine.prototype.getQueryResult = function (query) {
  17163. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17164. };
  17165. /**
  17166. * Initiates an occlusion query
  17167. * @param algorithmType defines the algorithm to use
  17168. * @param query defines the query to use
  17169. * @returns the current engine
  17170. * @see http://doc.babylonjs.com/features/occlusionquery
  17171. */
  17172. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17173. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17174. this._gl.beginQuery(glAlgorithm, query);
  17175. return this;
  17176. };
  17177. /**
  17178. * Ends an occlusion query
  17179. * @see http://doc.babylonjs.com/features/occlusionquery
  17180. * @param algorithmType defines the algorithm to use
  17181. * @returns the current engine
  17182. */
  17183. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17184. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17185. this._gl.endQuery(glAlgorithm);
  17186. return this;
  17187. };
  17188. /* Time queries */
  17189. Engine.prototype._createTimeQuery = function () {
  17190. var timerQuery = this._caps.timerQuery;
  17191. if (timerQuery.createQueryEXT) {
  17192. return timerQuery.createQueryEXT();
  17193. }
  17194. return this.createQuery();
  17195. };
  17196. Engine.prototype._deleteTimeQuery = function (query) {
  17197. var timerQuery = this._caps.timerQuery;
  17198. if (timerQuery.deleteQueryEXT) {
  17199. timerQuery.deleteQueryEXT(query);
  17200. return;
  17201. }
  17202. this.deleteQuery(query);
  17203. };
  17204. Engine.prototype._getTimeQueryResult = function (query) {
  17205. var timerQuery = this._caps.timerQuery;
  17206. if (timerQuery.getQueryObjectEXT) {
  17207. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17208. }
  17209. return this.getQueryResult(query);
  17210. };
  17211. Engine.prototype._getTimeQueryAvailability = function (query) {
  17212. var timerQuery = this._caps.timerQuery;
  17213. if (timerQuery.getQueryObjectEXT) {
  17214. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17215. }
  17216. return this.isQueryResultAvailable(query);
  17217. };
  17218. /**
  17219. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17220. * Please note that only one query can be issued at a time
  17221. * @returns a time token used to track the time span
  17222. */
  17223. Engine.prototype.startTimeQuery = function () {
  17224. var timerQuery = this._caps.timerQuery;
  17225. if (!timerQuery) {
  17226. return null;
  17227. }
  17228. var token = new BABYLON._TimeToken();
  17229. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17230. if (this._caps.canUseTimestampForTimerQuery) {
  17231. token._startTimeQuery = this._createTimeQuery();
  17232. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17233. }
  17234. else {
  17235. if (this._currentNonTimestampToken) {
  17236. return this._currentNonTimestampToken;
  17237. }
  17238. token._timeElapsedQuery = this._createTimeQuery();
  17239. if (timerQuery.beginQueryEXT) {
  17240. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17241. }
  17242. else {
  17243. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17244. }
  17245. this._currentNonTimestampToken = token;
  17246. }
  17247. return token;
  17248. };
  17249. /**
  17250. * Ends a time query
  17251. * @param token defines the token used to measure the time span
  17252. * @returns the time spent (in ns)
  17253. */
  17254. Engine.prototype.endTimeQuery = function (token) {
  17255. var timerQuery = this._caps.timerQuery;
  17256. if (!timerQuery || !token) {
  17257. return -1;
  17258. }
  17259. if (this._caps.canUseTimestampForTimerQuery) {
  17260. if (!token._startTimeQuery) {
  17261. return -1;
  17262. }
  17263. if (!token._endTimeQuery) {
  17264. token._endTimeQuery = this._createTimeQuery();
  17265. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17266. }
  17267. }
  17268. else if (!token._timeElapsedQueryEnded) {
  17269. if (!token._timeElapsedQuery) {
  17270. return -1;
  17271. }
  17272. if (timerQuery.endQueryEXT) {
  17273. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17274. }
  17275. else {
  17276. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17277. }
  17278. token._timeElapsedQueryEnded = true;
  17279. }
  17280. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17281. var available = false;
  17282. if (token._endTimeQuery) {
  17283. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17284. }
  17285. else if (token._timeElapsedQuery) {
  17286. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17287. }
  17288. if (available && !disjoint) {
  17289. var result = 0;
  17290. if (this._caps.canUseTimestampForTimerQuery) {
  17291. if (!token._startTimeQuery || !token._endTimeQuery) {
  17292. return -1;
  17293. }
  17294. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17295. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17296. result = timeEnd - timeStart;
  17297. this._deleteTimeQuery(token._startTimeQuery);
  17298. this._deleteTimeQuery(token._endTimeQuery);
  17299. token._startTimeQuery = null;
  17300. token._endTimeQuery = null;
  17301. }
  17302. else {
  17303. if (!token._timeElapsedQuery) {
  17304. return -1;
  17305. }
  17306. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17307. this._deleteTimeQuery(token._timeElapsedQuery);
  17308. token._timeElapsedQuery = null;
  17309. token._timeElapsedQueryEnded = false;
  17310. this._currentNonTimestampToken = null;
  17311. }
  17312. return result;
  17313. }
  17314. return -1;
  17315. };
  17316. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17317. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17318. };
  17319. // Transform feedback
  17320. /**
  17321. * Creates a webGL transform feedback object
  17322. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17323. * @returns the webGL transform feedback object
  17324. */
  17325. Engine.prototype.createTransformFeedback = function () {
  17326. return this._gl.createTransformFeedback();
  17327. };
  17328. /**
  17329. * Delete a webGL transform feedback object
  17330. * @param value defines the webGL transform feedback object to delete
  17331. */
  17332. Engine.prototype.deleteTransformFeedback = function (value) {
  17333. this._gl.deleteTransformFeedback(value);
  17334. };
  17335. /**
  17336. * Bind a webGL transform feedback object to the webgl context
  17337. * @param value defines the webGL transform feedback object to bind
  17338. */
  17339. Engine.prototype.bindTransformFeedback = function (value) {
  17340. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17341. };
  17342. /**
  17343. * Begins a transform feedback operation
  17344. * @param usePoints defines if points or triangles must be used
  17345. */
  17346. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17347. if (usePoints === void 0) { usePoints = true; }
  17348. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17349. };
  17350. /**
  17351. * Ends a transform feedback operation
  17352. */
  17353. Engine.prototype.endTransformFeedback = function () {
  17354. this._gl.endTransformFeedback();
  17355. };
  17356. /**
  17357. * Specify the varyings to use with transform feedback
  17358. * @param program defines the associated webGL program
  17359. * @param value defines the list of strings representing the varying names
  17360. */
  17361. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17362. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17363. };
  17364. /**
  17365. * Bind a webGL buffer for a transform feedback operation
  17366. * @param value defines the webGL buffer to bind
  17367. */
  17368. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17369. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17370. };
  17371. /** @hidden */
  17372. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17373. var _this = this;
  17374. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17375. this._activeRequests.push(request);
  17376. request.onCompleteObservable.add(function (request) {
  17377. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17378. });
  17379. return request;
  17380. };
  17381. /** @hidden */
  17382. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17383. var _this = this;
  17384. return new Promise(function (resolve, reject) {
  17385. _this._loadFile(url, function (data) {
  17386. resolve(data);
  17387. }, undefined, database, useArrayBuffer, function (request, exception) {
  17388. reject(exception);
  17389. });
  17390. });
  17391. };
  17392. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17393. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17394. var onload = function (data) {
  17395. loadedFiles[index] = data;
  17396. loadedFiles._internalCount++;
  17397. if (loadedFiles._internalCount === 6) {
  17398. onfinish(loadedFiles);
  17399. }
  17400. };
  17401. var onerror = function (request, exception) {
  17402. if (onErrorCallBack && request) {
  17403. onErrorCallBack(request.status + " " + request.statusText, exception);
  17404. }
  17405. };
  17406. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17407. };
  17408. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17409. if (onError === void 0) { onError = null; }
  17410. var loadedFiles = [];
  17411. loadedFiles._internalCount = 0;
  17412. for (var index = 0; index < 6; index++) {
  17413. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17414. }
  17415. };
  17416. // Statics
  17417. /**
  17418. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17419. * @returns true if the engine can be created
  17420. * @ignorenaming
  17421. */
  17422. Engine.isSupported = function () {
  17423. try {
  17424. var tempcanvas = document.createElement("canvas");
  17425. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17426. return gl != null && !!window.WebGLRenderingContext;
  17427. }
  17428. catch (e) {
  17429. return false;
  17430. }
  17431. };
  17432. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17433. Engine.ExceptionList = [
  17434. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17435. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17436. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17437. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17438. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17439. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17440. ];
  17441. /** Gets the list of created engines */
  17442. Engine.Instances = new Array();
  17443. // Const statics
  17444. Engine._ALPHA_DISABLE = 0;
  17445. Engine._ALPHA_ADD = 1;
  17446. Engine._ALPHA_COMBINE = 2;
  17447. Engine._ALPHA_SUBTRACT = 3;
  17448. Engine._ALPHA_MULTIPLY = 4;
  17449. Engine._ALPHA_MAXIMIZED = 5;
  17450. Engine._ALPHA_ONEONE = 6;
  17451. Engine._ALPHA_PREMULTIPLIED = 7;
  17452. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17453. Engine._ALPHA_INTERPOLATE = 9;
  17454. Engine._ALPHA_SCREENMODE = 10;
  17455. Engine._DELAYLOADSTATE_NONE = 0;
  17456. Engine._DELAYLOADSTATE_LOADED = 1;
  17457. Engine._DELAYLOADSTATE_LOADING = 2;
  17458. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17459. Engine._TEXTUREFORMAT_ALPHA = 0;
  17460. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17461. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17462. Engine._TEXTUREFORMAT_RGB = 4;
  17463. Engine._TEXTUREFORMAT_RGBA = 5;
  17464. Engine._TEXTUREFORMAT_R = 6;
  17465. Engine._TEXTUREFORMAT_RG = 7;
  17466. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17467. Engine._TEXTURETYPE_FLOAT = 1;
  17468. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17469. // Depht or Stencil test Constants.
  17470. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17471. 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.
  17472. 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.
  17473. 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.
  17474. 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.
  17475. 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.
  17476. 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.
  17477. 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.
  17478. // Stencil Actions Constants.
  17479. Engine._KEEP = 0x1E00;
  17480. Engine._REPLACE = 0x1E01;
  17481. Engine._INCR = 0x1E02;
  17482. Engine._DECR = 0x1E03;
  17483. Engine._INVERT = 0x150A;
  17484. Engine._INCR_WRAP = 0x8507;
  17485. Engine._DECR_WRAP = 0x8508;
  17486. // Texture rescaling mode
  17487. Engine._SCALEMODE_FLOOR = 1;
  17488. Engine._SCALEMODE_NEAREST = 2;
  17489. Engine._SCALEMODE_CEILING = 3;
  17490. // Updatable statics so stick with vars here
  17491. /**
  17492. * Gets or sets the epsilon value used by collision engine
  17493. */
  17494. Engine.CollisionsEpsilon = 0.001;
  17495. /**
  17496. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17497. */
  17498. Engine.CodeRepository = "src/";
  17499. /**
  17500. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17501. */
  17502. Engine.ShadersRepository = "src/Shaders/";
  17503. return Engine;
  17504. }());
  17505. BABYLON.Engine = Engine;
  17506. })(BABYLON || (BABYLON = {}));
  17507. //# sourceMappingURL=babylon.engine.js.map
  17508. var BABYLON;
  17509. (function (BABYLON) {
  17510. /**
  17511. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17512. */
  17513. var Node = /** @class */ (function () {
  17514. /**
  17515. * Creates a new Node
  17516. * @param {string} name - the name and id to be given to this node
  17517. * @param {BABYLON.Scene} the scene this node will be added to
  17518. */
  17519. function Node(name, scene) {
  17520. if (scene === void 0) { scene = null; }
  17521. /**
  17522. * Gets or sets a string used to store user defined state for the node
  17523. */
  17524. this.state = "";
  17525. /**
  17526. * Gets or sets an object used to store user defined information for the node
  17527. */
  17528. this.metadata = null;
  17529. /**
  17530. * Gets or sets a boolean used to define if the node must be serialized
  17531. */
  17532. this.doNotSerialize = false;
  17533. /** @hidden */
  17534. this._isDisposed = false;
  17535. /**
  17536. * Gets a list of Animations associated with the node
  17537. */
  17538. this.animations = new Array();
  17539. this._ranges = {};
  17540. this._isEnabled = true;
  17541. this._isReady = true;
  17542. /** @hidden */
  17543. this._currentRenderId = -1;
  17544. this._parentRenderId = -1;
  17545. this._childRenderId = -1;
  17546. this._animationPropertiesOverride = null;
  17547. /**
  17548. * An event triggered when the mesh is disposed
  17549. */
  17550. this.onDisposeObservable = new BABYLON.Observable();
  17551. // Behaviors
  17552. this._behaviors = new Array();
  17553. this.name = name;
  17554. this.id = name;
  17555. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17556. this.uniqueId = this._scene.getUniqueId();
  17557. this._initCache();
  17558. }
  17559. /**
  17560. * Gets a boolean indicating if the node has been disposed
  17561. * @returns true if the node was disposed
  17562. */
  17563. Node.prototype.isDisposed = function () {
  17564. return this._isDisposed;
  17565. };
  17566. Object.defineProperty(Node.prototype, "parent", {
  17567. get: function () {
  17568. return this._parentNode;
  17569. },
  17570. /**
  17571. * Gets or sets the parent of the node
  17572. */
  17573. set: function (parent) {
  17574. if (this._parentNode === parent) {
  17575. return;
  17576. }
  17577. // Remove self from list of children of parent
  17578. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17579. var index = this._parentNode._children.indexOf(this);
  17580. if (index !== -1) {
  17581. this._parentNode._children.splice(index, 1);
  17582. }
  17583. }
  17584. // Store new parent
  17585. this._parentNode = parent;
  17586. // Add as child to new parent
  17587. if (this._parentNode) {
  17588. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17589. this._parentNode._children = new Array();
  17590. }
  17591. this._parentNode._children.push(this);
  17592. }
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17598. /**
  17599. * Gets or sets the animation properties override
  17600. */
  17601. get: function () {
  17602. if (!this._animationPropertiesOverride) {
  17603. return this._scene.animationPropertiesOverride;
  17604. }
  17605. return this._animationPropertiesOverride;
  17606. },
  17607. set: function (value) {
  17608. this._animationPropertiesOverride = value;
  17609. },
  17610. enumerable: true,
  17611. configurable: true
  17612. });
  17613. /**
  17614. * Gets a string idenfifying the name of the class
  17615. * @returns "Node" string
  17616. */
  17617. Node.prototype.getClassName = function () {
  17618. return "Node";
  17619. };
  17620. Object.defineProperty(Node.prototype, "onDispose", {
  17621. /**
  17622. * Sets a callback that will be raised when the node will be disposed
  17623. */
  17624. set: function (callback) {
  17625. if (this._onDisposeObserver) {
  17626. this.onDisposeObservable.remove(this._onDisposeObserver);
  17627. }
  17628. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. /**
  17634. * Gets the scene of the node
  17635. * @returns a {BABYLON.Scene}
  17636. */
  17637. Node.prototype.getScene = function () {
  17638. return this._scene;
  17639. };
  17640. /**
  17641. * Gets the engine of the node
  17642. * @returns a {BABYLON.Engine}
  17643. */
  17644. Node.prototype.getEngine = function () {
  17645. return this._scene.getEngine();
  17646. };
  17647. /**
  17648. * Attach a behavior to the node
  17649. * @see http://doc.babylonjs.com/features/behaviour
  17650. * @param behavior defines the behavior to attach
  17651. * @returns the current Node
  17652. */
  17653. Node.prototype.addBehavior = function (behavior) {
  17654. var _this = this;
  17655. var index = this._behaviors.indexOf(behavior);
  17656. if (index !== -1) {
  17657. return this;
  17658. }
  17659. behavior.init();
  17660. if (this._scene.isLoading) {
  17661. // We defer the attach when the scene will be loaded
  17662. this._scene.onDataLoadedObservable.addOnce(function () {
  17663. behavior.attach(_this);
  17664. });
  17665. }
  17666. else {
  17667. behavior.attach(this);
  17668. }
  17669. this._behaviors.push(behavior);
  17670. return this;
  17671. };
  17672. /**
  17673. * Remove an attached behavior
  17674. * @see http://doc.babylonjs.com/features/behaviour
  17675. * @param behavior defines the behavior to attach
  17676. * @returns the current Node
  17677. */
  17678. Node.prototype.removeBehavior = function (behavior) {
  17679. var index = this._behaviors.indexOf(behavior);
  17680. if (index === -1) {
  17681. return this;
  17682. }
  17683. this._behaviors[index].detach();
  17684. this._behaviors.splice(index, 1);
  17685. return this;
  17686. };
  17687. Object.defineProperty(Node.prototype, "behaviors", {
  17688. /**
  17689. * Gets the list of attached behaviors
  17690. * @see http://doc.babylonjs.com/features/behaviour
  17691. */
  17692. get: function () {
  17693. return this._behaviors;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. /**
  17699. * Gets an attached behavior by name
  17700. * @param name defines the name of the behavior to look for
  17701. * @see http://doc.babylonjs.com/features/behaviour
  17702. * @returns null if behavior was not found else the requested behavior
  17703. */
  17704. Node.prototype.getBehaviorByName = function (name) {
  17705. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17706. var behavior = _a[_i];
  17707. if (behavior.name === name) {
  17708. return behavior;
  17709. }
  17710. }
  17711. return null;
  17712. };
  17713. /**
  17714. * Returns the world matrix of the node
  17715. * @returns a matrix containing the node's world matrix
  17716. */
  17717. Node.prototype.getWorldMatrix = function () {
  17718. return BABYLON.Matrix.Identity();
  17719. };
  17720. /** @hidden */
  17721. Node.prototype._getWorldMatrixDeterminant = function () {
  17722. return 1;
  17723. };
  17724. // override it in derived class if you add new variables to the cache
  17725. // and call the parent class method
  17726. /** @hidden */
  17727. Node.prototype._initCache = function () {
  17728. this._cache = {};
  17729. this._cache.parent = undefined;
  17730. };
  17731. /** @hidden */
  17732. Node.prototype.updateCache = function (force) {
  17733. if (!force && this.isSynchronized())
  17734. return;
  17735. this._cache.parent = this.parent;
  17736. this._updateCache();
  17737. };
  17738. // override it in derived class if you add new variables to the cache
  17739. // and call the parent class method if !ignoreParentClass
  17740. /** @hidden */
  17741. Node.prototype._updateCache = function (ignoreParentClass) {
  17742. };
  17743. // override it in derived class if you add new variables to the cache
  17744. /** @hidden */
  17745. Node.prototype._isSynchronized = function () {
  17746. return true;
  17747. };
  17748. /** @hidden */
  17749. Node.prototype._markSyncedWithParent = function () {
  17750. if (this.parent) {
  17751. this._parentRenderId = this.parent._childRenderId;
  17752. }
  17753. };
  17754. /** @hidden */
  17755. Node.prototype.isSynchronizedWithParent = function () {
  17756. if (!this.parent) {
  17757. return true;
  17758. }
  17759. if (this._parentRenderId !== this.parent._childRenderId) {
  17760. return false;
  17761. }
  17762. return this.parent.isSynchronized();
  17763. };
  17764. /** @hidden */
  17765. Node.prototype.isSynchronized = function (updateCache) {
  17766. var check = this.hasNewParent();
  17767. check = check || !this.isSynchronizedWithParent();
  17768. check = check || !this._isSynchronized();
  17769. if (updateCache)
  17770. this.updateCache(true);
  17771. return !check;
  17772. };
  17773. /** @hidden */
  17774. Node.prototype.hasNewParent = function (update) {
  17775. if (this._cache.parent === this.parent)
  17776. return false;
  17777. if (update)
  17778. this._cache.parent = this.parent;
  17779. return true;
  17780. };
  17781. /**
  17782. * Is this node ready to be used/rendered
  17783. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17784. * @return true if the node is ready
  17785. */
  17786. Node.prototype.isReady = function (completeCheck) {
  17787. if (completeCheck === void 0) { completeCheck = false; }
  17788. return this._isReady;
  17789. };
  17790. /**
  17791. * Is this node enabled?
  17792. * 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
  17793. * @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
  17794. * @return whether this node (and its parent) is enabled
  17795. */
  17796. Node.prototype.isEnabled = function (checkAncestors) {
  17797. if (checkAncestors === void 0) { checkAncestors = true; }
  17798. if (checkAncestors === false) {
  17799. return this._isEnabled;
  17800. }
  17801. if (this._isEnabled === false) {
  17802. return false;
  17803. }
  17804. if (this.parent !== undefined && this.parent !== null) {
  17805. return this.parent.isEnabled(checkAncestors);
  17806. }
  17807. return true;
  17808. };
  17809. /**
  17810. * Set the enabled state of this node
  17811. * @param value defines the new enabled state
  17812. */
  17813. Node.prototype.setEnabled = function (value) {
  17814. this._isEnabled = value;
  17815. };
  17816. /**
  17817. * Is this node a descendant of the given node?
  17818. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17819. * @param ancestor defines the parent node to inspect
  17820. * @returns a boolean indicating if this node is a descendant of the given node
  17821. */
  17822. Node.prototype.isDescendantOf = function (ancestor) {
  17823. if (this.parent) {
  17824. if (this.parent === ancestor) {
  17825. return true;
  17826. }
  17827. return this.parent.isDescendantOf(ancestor);
  17828. }
  17829. return false;
  17830. };
  17831. /** @hidden */
  17832. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17833. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17834. if (!this._children) {
  17835. return;
  17836. }
  17837. for (var index = 0; index < this._children.length; index++) {
  17838. var item = this._children[index];
  17839. if (!predicate || predicate(item)) {
  17840. results.push(item);
  17841. }
  17842. if (!directDescendantsOnly) {
  17843. item._getDescendants(results, false, predicate);
  17844. }
  17845. }
  17846. };
  17847. /**
  17848. * Will return all nodes that have this node as ascendant
  17849. * @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
  17850. * @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
  17851. * @return all children nodes of all types
  17852. */
  17853. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17854. var results = new Array();
  17855. this._getDescendants(results, directDescendantsOnly, predicate);
  17856. return results;
  17857. };
  17858. /**
  17859. * Get all child-meshes of this node
  17860. * @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
  17861. * @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
  17862. * @returns an array of {BABYLON.AbstractMesh}
  17863. */
  17864. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17865. var results = [];
  17866. this._getDescendants(results, directDescendantsOnly, function (node) {
  17867. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17868. });
  17869. return results;
  17870. };
  17871. /**
  17872. * Get all child-transformNodes of this node
  17873. * @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
  17874. * @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
  17875. * @returns an array of {BABYLON.TransformNode}
  17876. */
  17877. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17878. var results = [];
  17879. this._getDescendants(results, directDescendantsOnly, function (node) {
  17880. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17881. });
  17882. return results;
  17883. };
  17884. /**
  17885. * Get all direct children of this node
  17886. * @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
  17887. * @returns an array of {BABYLON.Node}
  17888. */
  17889. Node.prototype.getChildren = function (predicate) {
  17890. return this.getDescendants(true, predicate);
  17891. };
  17892. /** @hidden */
  17893. Node.prototype._setReady = function (state) {
  17894. if (state === this._isReady) {
  17895. return;
  17896. }
  17897. if (!state) {
  17898. this._isReady = false;
  17899. return;
  17900. }
  17901. if (this.onReady) {
  17902. this.onReady(this);
  17903. }
  17904. this._isReady = true;
  17905. };
  17906. /**
  17907. * Get an animation by name
  17908. * @param name defines the name of the animation to look for
  17909. * @returns null if not found else the requested animation
  17910. */
  17911. Node.prototype.getAnimationByName = function (name) {
  17912. for (var i = 0; i < this.animations.length; i++) {
  17913. var animation = this.animations[i];
  17914. if (animation.name === name) {
  17915. return animation;
  17916. }
  17917. }
  17918. return null;
  17919. };
  17920. /**
  17921. * Creates an animation range for this node
  17922. * @param name defines the name of the range
  17923. * @param from defines the starting key
  17924. * @param to defines the end key
  17925. */
  17926. Node.prototype.createAnimationRange = function (name, from, to) {
  17927. // check name not already in use
  17928. if (!this._ranges[name]) {
  17929. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17930. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17931. if (this.animations[i]) {
  17932. this.animations[i].createRange(name, from, to);
  17933. }
  17934. }
  17935. }
  17936. };
  17937. /**
  17938. * Delete a specific animation range
  17939. * @param name defines the name of the range to delete
  17940. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17941. */
  17942. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17943. if (deleteFrames === void 0) { deleteFrames = true; }
  17944. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17945. if (this.animations[i]) {
  17946. this.animations[i].deleteRange(name, deleteFrames);
  17947. }
  17948. }
  17949. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17950. };
  17951. /**
  17952. * Get an animation range by name
  17953. * @param name defines the name of the animation range to look for
  17954. * @returns null if not found else the requested animation range
  17955. */
  17956. Node.prototype.getAnimationRange = function (name) {
  17957. return this._ranges[name];
  17958. };
  17959. /**
  17960. * Will start the animation sequence
  17961. * @param name defines the range frames for animation sequence
  17962. * @param loop defines if the animation should loop (false by default)
  17963. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17964. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17965. * @returns the object created for this animation. If range does not exist, it will return null
  17966. */
  17967. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17968. var range = this.getAnimationRange(name);
  17969. if (!range) {
  17970. return null;
  17971. }
  17972. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17973. };
  17974. /**
  17975. * Serialize animation ranges into a JSON compatible object
  17976. * @returns serialization object
  17977. */
  17978. Node.prototype.serializeAnimationRanges = function () {
  17979. var serializationRanges = [];
  17980. for (var name in this._ranges) {
  17981. var localRange = this._ranges[name];
  17982. if (!localRange) {
  17983. continue;
  17984. }
  17985. var range = {};
  17986. range.name = name;
  17987. range.from = localRange.from;
  17988. range.to = localRange.to;
  17989. serializationRanges.push(range);
  17990. }
  17991. return serializationRanges;
  17992. };
  17993. /**
  17994. * Computes the world matrix of the node
  17995. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17996. * @returns the world matrix
  17997. */
  17998. Node.prototype.computeWorldMatrix = function (force) {
  17999. return BABYLON.Matrix.Identity();
  18000. };
  18001. /**
  18002. * Releases resources associated with this node.
  18003. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18004. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18005. */
  18006. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18007. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18008. if (!doNotRecurse) {
  18009. var nodes = this.getDescendants(true);
  18010. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18011. var node = nodes_1[_i];
  18012. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18013. }
  18014. }
  18015. else {
  18016. var transformNodes = this.getChildTransformNodes(true);
  18017. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18018. var transformNode = transformNodes_1[_a];
  18019. transformNode.parent = null;
  18020. transformNode.computeWorldMatrix(true);
  18021. }
  18022. }
  18023. this.parent = null;
  18024. // Callback
  18025. this.onDisposeObservable.notifyObservers(this);
  18026. this.onDisposeObservable.clear();
  18027. // Behaviors
  18028. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18029. var behavior = _c[_b];
  18030. behavior.detach();
  18031. }
  18032. this._behaviors = [];
  18033. this._isDisposed = true;
  18034. };
  18035. /**
  18036. * Parse animation range data from a serialization object and store them into a given node
  18037. * @param node defines where to store the animation ranges
  18038. * @param parsedNode defines the serialization object to read data from
  18039. * @param scene defines the hosting scene
  18040. */
  18041. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18042. if (parsedNode.ranges) {
  18043. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18044. var data = parsedNode.ranges[index];
  18045. node.createAnimationRange(data.name, data.from, data.to);
  18046. }
  18047. }
  18048. };
  18049. __decorate([
  18050. BABYLON.serialize()
  18051. ], Node.prototype, "name", void 0);
  18052. __decorate([
  18053. BABYLON.serialize()
  18054. ], Node.prototype, "id", void 0);
  18055. __decorate([
  18056. BABYLON.serialize()
  18057. ], Node.prototype, "uniqueId", void 0);
  18058. __decorate([
  18059. BABYLON.serialize()
  18060. ], Node.prototype, "state", void 0);
  18061. __decorate([
  18062. BABYLON.serialize()
  18063. ], Node.prototype, "metadata", void 0);
  18064. return Node;
  18065. }());
  18066. BABYLON.Node = Node;
  18067. })(BABYLON || (BABYLON = {}));
  18068. //# sourceMappingURL=babylon.node.js.map
  18069. var BABYLON;
  18070. (function (BABYLON) {
  18071. var BoundingSphere = /** @class */ (function () {
  18072. /**
  18073. * Creates a new bounding sphere
  18074. * @param min defines the minimum vector (in local space)
  18075. * @param max defines the maximum vector (in local space)
  18076. */
  18077. function BoundingSphere(min, max) {
  18078. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18079. this.reConstruct(min, max);
  18080. }
  18081. /**
  18082. * Recreates the entire bounding sphere from scratch
  18083. * @param min defines the new minimum vector (in local space)
  18084. * @param max defines the new maximum vector (in local space)
  18085. */
  18086. BoundingSphere.prototype.reConstruct = function (min, max) {
  18087. this.minimum = min.clone();
  18088. this.maximum = max.clone();
  18089. var distance = BABYLON.Vector3.Distance(min, max);
  18090. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18091. this.radius = distance * 0.5;
  18092. this.centerWorld = BABYLON.Vector3.Zero();
  18093. this._update(BABYLON.Matrix.Identity());
  18094. };
  18095. // Methods
  18096. BoundingSphere.prototype._update = function (world) {
  18097. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18098. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18099. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18100. };
  18101. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18102. for (var i = 0; i < 6; i++) {
  18103. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18104. return false;
  18105. }
  18106. return true;
  18107. };
  18108. BoundingSphere.prototype.intersectsPoint = function (point) {
  18109. var x = this.centerWorld.x - point.x;
  18110. var y = this.centerWorld.y - point.y;
  18111. var z = this.centerWorld.z - point.z;
  18112. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18113. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18114. return false;
  18115. return true;
  18116. };
  18117. // Statics
  18118. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18119. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18120. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18121. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18122. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18123. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18124. return false;
  18125. return true;
  18126. };
  18127. return BoundingSphere;
  18128. }());
  18129. BABYLON.BoundingSphere = BoundingSphere;
  18130. })(BABYLON || (BABYLON = {}));
  18131. //# sourceMappingURL=babylon.boundingSphere.js.map
  18132. var BABYLON;
  18133. (function (BABYLON) {
  18134. var BoundingBox = /** @class */ (function () {
  18135. /**
  18136. * Creates a new bounding box
  18137. * @param min defines the minimum vector (in local space)
  18138. * @param max defines the maximum vector (in local space)
  18139. */
  18140. function BoundingBox(min, max) {
  18141. this.vectorsWorld = new Array();
  18142. this.reConstruct(min, max);
  18143. }
  18144. // Methods
  18145. /**
  18146. * Recreates the entire bounding box from scratch
  18147. * @param min defines the new minimum vector (in local space)
  18148. * @param max defines the new maximum vector (in local space)
  18149. */
  18150. BoundingBox.prototype.reConstruct = function (min, max) {
  18151. this.minimum = min.clone();
  18152. this.maximum = max.clone();
  18153. // Bounding vectors
  18154. this.vectors = new Array();
  18155. this.vectors.push(this.minimum.clone());
  18156. this.vectors.push(this.maximum.clone());
  18157. this.vectors.push(this.minimum.clone());
  18158. this.vectors[2].x = this.maximum.x;
  18159. this.vectors.push(this.minimum.clone());
  18160. this.vectors[3].y = this.maximum.y;
  18161. this.vectors.push(this.minimum.clone());
  18162. this.vectors[4].z = this.maximum.z;
  18163. this.vectors.push(this.maximum.clone());
  18164. this.vectors[5].z = this.minimum.z;
  18165. this.vectors.push(this.maximum.clone());
  18166. this.vectors[6].x = this.minimum.x;
  18167. this.vectors.push(this.maximum.clone());
  18168. this.vectors[7].y = this.minimum.y;
  18169. // OBB
  18170. this.center = this.maximum.add(this.minimum).scale(0.5);
  18171. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18172. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18173. // World
  18174. for (var index = 0; index < this.vectors.length; index++) {
  18175. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18176. }
  18177. this.minimumWorld = BABYLON.Vector3.Zero();
  18178. this.maximumWorld = BABYLON.Vector3.Zero();
  18179. this.centerWorld = BABYLON.Vector3.Zero();
  18180. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18181. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18182. };
  18183. BoundingBox.prototype.getWorldMatrix = function () {
  18184. return this._worldMatrix;
  18185. };
  18186. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18187. this._worldMatrix.copyFrom(matrix);
  18188. return this;
  18189. };
  18190. BoundingBox.prototype._update = function (world) {
  18191. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18192. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18193. for (var index = 0; index < this.vectors.length; index++) {
  18194. var v = this.vectorsWorld[index];
  18195. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18196. if (v.x < this.minimumWorld.x)
  18197. this.minimumWorld.x = v.x;
  18198. if (v.y < this.minimumWorld.y)
  18199. this.minimumWorld.y = v.y;
  18200. if (v.z < this.minimumWorld.z)
  18201. this.minimumWorld.z = v.z;
  18202. if (v.x > this.maximumWorld.x)
  18203. this.maximumWorld.x = v.x;
  18204. if (v.y > this.maximumWorld.y)
  18205. this.maximumWorld.y = v.y;
  18206. if (v.z > this.maximumWorld.z)
  18207. this.maximumWorld.z = v.z;
  18208. }
  18209. // Extend
  18210. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18211. this.extendSizeWorld.scaleInPlace(0.5);
  18212. // OBB
  18213. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18214. this.centerWorld.scaleInPlace(0.5);
  18215. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18216. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18217. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18218. this._worldMatrix = world;
  18219. };
  18220. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18221. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18222. };
  18223. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18224. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18225. };
  18226. BoundingBox.prototype.intersectsPoint = function (point) {
  18227. var delta = -BABYLON.Epsilon;
  18228. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18229. return false;
  18230. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18231. return false;
  18232. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18233. return false;
  18234. return true;
  18235. };
  18236. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18237. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18238. };
  18239. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18240. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18241. return false;
  18242. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18243. return false;
  18244. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18245. return false;
  18246. return true;
  18247. };
  18248. // Statics
  18249. BoundingBox.Intersects = function (box0, box1) {
  18250. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18251. return false;
  18252. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18253. return false;
  18254. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18255. return false;
  18256. return true;
  18257. };
  18258. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18259. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18260. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18261. return (num <= (sphereRadius * sphereRadius));
  18262. };
  18263. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18264. for (var p = 0; p < 6; p++) {
  18265. for (var i = 0; i < 8; i++) {
  18266. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18267. return false;
  18268. }
  18269. }
  18270. }
  18271. return true;
  18272. };
  18273. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18274. for (var p = 0; p < 6; p++) {
  18275. var inCount = 8;
  18276. for (var i = 0; i < 8; i++) {
  18277. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18278. --inCount;
  18279. }
  18280. else {
  18281. break;
  18282. }
  18283. }
  18284. if (inCount === 0)
  18285. return false;
  18286. }
  18287. return true;
  18288. };
  18289. return BoundingBox;
  18290. }());
  18291. BABYLON.BoundingBox = BoundingBox;
  18292. })(BABYLON || (BABYLON = {}));
  18293. //# sourceMappingURL=babylon.boundingBox.js.map
  18294. var BABYLON;
  18295. (function (BABYLON) {
  18296. var computeBoxExtents = function (axis, box) {
  18297. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18298. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18299. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18300. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18301. var r = r0 + r1 + r2;
  18302. return {
  18303. min: p - r,
  18304. max: p + r
  18305. };
  18306. };
  18307. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18308. var axisOverlap = function (axis, box0, box1) {
  18309. var result0 = computeBoxExtents(axis, box0);
  18310. var result1 = computeBoxExtents(axis, box1);
  18311. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18312. };
  18313. var BoundingInfo = /** @class */ (function () {
  18314. function BoundingInfo(minimum, maximum) {
  18315. this.minimum = minimum;
  18316. this.maximum = maximum;
  18317. this._isLocked = false;
  18318. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18319. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18320. }
  18321. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18322. get: function () {
  18323. return this._isLocked;
  18324. },
  18325. set: function (value) {
  18326. this._isLocked = value;
  18327. },
  18328. enumerable: true,
  18329. configurable: true
  18330. });
  18331. // Methods
  18332. BoundingInfo.prototype.update = function (world) {
  18333. if (this._isLocked) {
  18334. return;
  18335. }
  18336. this.boundingBox._update(world);
  18337. this.boundingSphere._update(world);
  18338. };
  18339. /**
  18340. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18341. * @param center New center of the bounding info
  18342. * @param extend New extend of the bounding info
  18343. */
  18344. BoundingInfo.prototype.centerOn = function (center, extend) {
  18345. this.minimum = center.subtract(extend);
  18346. this.maximum = center.add(extend);
  18347. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18348. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18349. return this;
  18350. };
  18351. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18352. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18353. return false;
  18354. return this.boundingBox.isInFrustum(frustumPlanes);
  18355. };
  18356. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18357. /**
  18358. * Gets the world distance between the min and max points of the bounding box
  18359. */
  18360. get: function () {
  18361. var boundingBox = this.boundingBox;
  18362. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18363. return size.length();
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18369. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18370. };
  18371. BoundingInfo.prototype._checkCollision = function (collider) {
  18372. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18373. };
  18374. BoundingInfo.prototype.intersectsPoint = function (point) {
  18375. if (!this.boundingSphere.centerWorld) {
  18376. return false;
  18377. }
  18378. if (!this.boundingSphere.intersectsPoint(point)) {
  18379. return false;
  18380. }
  18381. if (!this.boundingBox.intersectsPoint(point)) {
  18382. return false;
  18383. }
  18384. return true;
  18385. };
  18386. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18387. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18388. return false;
  18389. }
  18390. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18391. return false;
  18392. }
  18393. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18394. return false;
  18395. }
  18396. if (!precise) {
  18397. return true;
  18398. }
  18399. var box0 = this.boundingBox;
  18400. var box1 = boundingInfo.boundingBox;
  18401. if (!axisOverlap(box0.directions[0], box0, box1))
  18402. return false;
  18403. if (!axisOverlap(box0.directions[1], box0, box1))
  18404. return false;
  18405. if (!axisOverlap(box0.directions[2], box0, box1))
  18406. return false;
  18407. if (!axisOverlap(box1.directions[0], box0, box1))
  18408. return false;
  18409. if (!axisOverlap(box1.directions[1], box0, box1))
  18410. return false;
  18411. if (!axisOverlap(box1.directions[2], box0, box1))
  18412. return false;
  18413. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18414. return false;
  18415. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18416. return false;
  18417. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18418. return false;
  18419. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18420. return false;
  18421. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18422. return false;
  18423. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18424. return false;
  18425. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18426. return false;
  18427. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18428. return false;
  18429. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18430. return false;
  18431. return true;
  18432. };
  18433. return BoundingInfo;
  18434. }());
  18435. BABYLON.BoundingInfo = BoundingInfo;
  18436. })(BABYLON || (BABYLON = {}));
  18437. //# sourceMappingURL=babylon.boundingInfo.js.map
  18438. var BABYLON;
  18439. (function (BABYLON) {
  18440. var TransformNode = /** @class */ (function (_super) {
  18441. __extends(TransformNode, _super);
  18442. function TransformNode(name, scene, isPure) {
  18443. if (scene === void 0) { scene = null; }
  18444. if (isPure === void 0) { isPure = true; }
  18445. var _this = _super.call(this, name, scene) || this;
  18446. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18447. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18448. _this._up = new BABYLON.Vector3(0, 1, 0);
  18449. _this._right = new BABYLON.Vector3(1, 0, 0);
  18450. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18451. // Properties
  18452. _this._rotation = BABYLON.Vector3.Zero();
  18453. _this._scaling = BABYLON.Vector3.One();
  18454. _this._isDirty = false;
  18455. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18456. _this.scalingDeterminant = 1;
  18457. _this.infiniteDistance = false;
  18458. /**
  18459. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18460. * By default the system will update normals to compensate
  18461. */
  18462. _this.ignoreNonUniformScaling = false;
  18463. _this.position = BABYLON.Vector3.Zero();
  18464. _this._localWorld = BABYLON.Matrix.Zero();
  18465. _this._worldMatrix = BABYLON.Matrix.Zero();
  18466. _this._worldMatrixDeterminant = 0;
  18467. _this._absolutePosition = BABYLON.Vector3.Zero();
  18468. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18469. _this._postMultiplyPivotMatrix = false;
  18470. _this._isWorldMatrixFrozen = false;
  18471. /**
  18472. * An event triggered after the world matrix is updated
  18473. */
  18474. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18475. _this._nonUniformScaling = false;
  18476. if (isPure) {
  18477. _this.getScene().addTransformNode(_this);
  18478. }
  18479. return _this;
  18480. }
  18481. /**
  18482. * Gets a string idenfifying the name of the class
  18483. * @returns "TransformNode" string
  18484. */
  18485. TransformNode.prototype.getClassName = function () {
  18486. return "TransformNode";
  18487. };
  18488. Object.defineProperty(TransformNode.prototype, "rotation", {
  18489. /**
  18490. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18491. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18492. * Default : (0.0, 0.0, 0.0)
  18493. */
  18494. get: function () {
  18495. return this._rotation;
  18496. },
  18497. set: function (newRotation) {
  18498. this._rotation = newRotation;
  18499. },
  18500. enumerable: true,
  18501. configurable: true
  18502. });
  18503. Object.defineProperty(TransformNode.prototype, "scaling", {
  18504. /**
  18505. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18506. * Default : (1.0, 1.0, 1.0)
  18507. */
  18508. get: function () {
  18509. return this._scaling;
  18510. },
  18511. /**
  18512. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18513. * Default : (1.0, 1.0, 1.0)
  18514. */
  18515. set: function (newScaling) {
  18516. this._scaling = newScaling;
  18517. },
  18518. enumerable: true,
  18519. configurable: true
  18520. });
  18521. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18522. /**
  18523. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18524. * It's null by default.
  18525. * 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)
  18526. */
  18527. get: function () {
  18528. return this._rotationQuaternion;
  18529. },
  18530. set: function (quaternion) {
  18531. this._rotationQuaternion = quaternion;
  18532. //reset the rotation vector.
  18533. if (quaternion && this.rotation.length()) {
  18534. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18535. }
  18536. },
  18537. enumerable: true,
  18538. configurable: true
  18539. });
  18540. Object.defineProperty(TransformNode.prototype, "forward", {
  18541. /**
  18542. * The forward direction of that transform in world space.
  18543. */
  18544. get: function () {
  18545. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18546. },
  18547. enumerable: true,
  18548. configurable: true
  18549. });
  18550. Object.defineProperty(TransformNode.prototype, "up", {
  18551. /**
  18552. * The up direction of that transform in world space.
  18553. */
  18554. get: function () {
  18555. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. Object.defineProperty(TransformNode.prototype, "right", {
  18561. /**
  18562. * The right direction of that transform in world space.
  18563. */
  18564. get: function () {
  18565. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18566. },
  18567. enumerable: true,
  18568. configurable: true
  18569. });
  18570. /**
  18571. * Returns the latest update of the World matrix
  18572. * Returns a Matrix.
  18573. */
  18574. TransformNode.prototype.getWorldMatrix = function () {
  18575. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18576. this.computeWorldMatrix();
  18577. }
  18578. return this._worldMatrix;
  18579. };
  18580. /** @hidden */
  18581. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18582. return this._worldMatrixDeterminant;
  18583. };
  18584. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18585. /**
  18586. * Returns directly the latest state of the mesh World matrix.
  18587. * A Matrix is returned.
  18588. */
  18589. get: function () {
  18590. return this._worldMatrix;
  18591. },
  18592. enumerable: true,
  18593. configurable: true
  18594. });
  18595. /**
  18596. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18597. * Returns the TransformNode.
  18598. */
  18599. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18600. this._poseMatrix.copyFrom(matrix);
  18601. return this;
  18602. };
  18603. /**
  18604. * Returns the mesh Pose matrix.
  18605. * Returned object : Matrix
  18606. */
  18607. TransformNode.prototype.getPoseMatrix = function () {
  18608. return this._poseMatrix;
  18609. };
  18610. TransformNode.prototype._isSynchronized = function () {
  18611. if (this._isDirty) {
  18612. return false;
  18613. }
  18614. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18615. return false;
  18616. if (this._cache.pivotMatrixUpdated) {
  18617. return false;
  18618. }
  18619. if (this.infiniteDistance) {
  18620. return false;
  18621. }
  18622. if (!this._cache.position.equals(this.position))
  18623. return false;
  18624. if (this.rotationQuaternion) {
  18625. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18626. return false;
  18627. }
  18628. if (!this._cache.rotation.equals(this.rotation))
  18629. return false;
  18630. if (!this._cache.scaling.equals(this.scaling))
  18631. return false;
  18632. return true;
  18633. };
  18634. TransformNode.prototype._initCache = function () {
  18635. _super.prototype._initCache.call(this);
  18636. this._cache.localMatrixUpdated = false;
  18637. this._cache.position = BABYLON.Vector3.Zero();
  18638. this._cache.scaling = BABYLON.Vector3.Zero();
  18639. this._cache.rotation = BABYLON.Vector3.Zero();
  18640. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18641. this._cache.billboardMode = -1;
  18642. };
  18643. TransformNode.prototype.markAsDirty = function (property) {
  18644. if (property === "rotation") {
  18645. this.rotationQuaternion = null;
  18646. }
  18647. this._currentRenderId = Number.MAX_VALUE;
  18648. this._isDirty = true;
  18649. return this;
  18650. };
  18651. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18652. /**
  18653. * Returns the current mesh absolute position.
  18654. * Retuns a Vector3.
  18655. */
  18656. get: function () {
  18657. return this._absolutePosition;
  18658. },
  18659. enumerable: true,
  18660. configurable: true
  18661. });
  18662. /**
  18663. * Sets a new matrix to apply before all other transformation
  18664. * @param matrix defines the transform matrix
  18665. * @returns the current TransformNode
  18666. */
  18667. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18668. return this.setPivotMatrix(matrix, false);
  18669. };
  18670. /**
  18671. * Sets a new pivot matrix to the current node
  18672. * @param matrix defines the new pivot matrix to use
  18673. * @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
  18674. * @returns the current TransformNode
  18675. */
  18676. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18677. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18678. this._pivotMatrix = matrix.clone();
  18679. this._cache.pivotMatrixUpdated = true;
  18680. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18681. if (this._postMultiplyPivotMatrix) {
  18682. if (!this._pivotMatrixInverse) {
  18683. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18684. }
  18685. else {
  18686. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18687. }
  18688. }
  18689. return this;
  18690. };
  18691. /**
  18692. * Returns the mesh pivot matrix.
  18693. * Default : Identity.
  18694. * A Matrix is returned.
  18695. */
  18696. TransformNode.prototype.getPivotMatrix = function () {
  18697. return this._pivotMatrix;
  18698. };
  18699. /**
  18700. * Prevents the World matrix to be computed any longer.
  18701. * Returns the TransformNode.
  18702. */
  18703. TransformNode.prototype.freezeWorldMatrix = function () {
  18704. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18705. this.computeWorldMatrix(true);
  18706. this._isWorldMatrixFrozen = true;
  18707. return this;
  18708. };
  18709. /**
  18710. * Allows back the World matrix computation.
  18711. * Returns the TransformNode.
  18712. */
  18713. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18714. this._isWorldMatrixFrozen = false;
  18715. this.computeWorldMatrix(true);
  18716. return this;
  18717. };
  18718. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18719. /**
  18720. * True if the World matrix has been frozen.
  18721. * Returns a boolean.
  18722. */
  18723. get: function () {
  18724. return this._isWorldMatrixFrozen;
  18725. },
  18726. enumerable: true,
  18727. configurable: true
  18728. });
  18729. /**
  18730. * Retuns the mesh absolute position in the World.
  18731. * Returns a Vector3.
  18732. */
  18733. TransformNode.prototype.getAbsolutePosition = function () {
  18734. this.computeWorldMatrix();
  18735. return this._absolutePosition;
  18736. };
  18737. /**
  18738. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18739. * Returns the TransformNode.
  18740. */
  18741. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18742. if (!absolutePosition) {
  18743. return this;
  18744. }
  18745. var absolutePositionX;
  18746. var absolutePositionY;
  18747. var absolutePositionZ;
  18748. if (absolutePosition.x === undefined) {
  18749. if (arguments.length < 3) {
  18750. return this;
  18751. }
  18752. absolutePositionX = arguments[0];
  18753. absolutePositionY = arguments[1];
  18754. absolutePositionZ = arguments[2];
  18755. }
  18756. else {
  18757. absolutePositionX = absolutePosition.x;
  18758. absolutePositionY = absolutePosition.y;
  18759. absolutePositionZ = absolutePosition.z;
  18760. }
  18761. if (this.parent) {
  18762. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18763. invertParentWorldMatrix.invert();
  18764. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18765. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18766. }
  18767. else {
  18768. this.position.x = absolutePositionX;
  18769. this.position.y = absolutePositionY;
  18770. this.position.z = absolutePositionZ;
  18771. }
  18772. return this;
  18773. };
  18774. /**
  18775. * Sets the mesh position in its local space.
  18776. * Returns the TransformNode.
  18777. */
  18778. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18779. this.computeWorldMatrix();
  18780. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18781. return this;
  18782. };
  18783. /**
  18784. * Returns the mesh position in the local space from the current World matrix values.
  18785. * Returns a new Vector3.
  18786. */
  18787. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18788. this.computeWorldMatrix();
  18789. var invLocalWorldMatrix = this._localWorld.clone();
  18790. invLocalWorldMatrix.invert();
  18791. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18792. };
  18793. /**
  18794. * Translates the mesh along the passed Vector3 in its local space.
  18795. * Returns the TransformNode.
  18796. */
  18797. TransformNode.prototype.locallyTranslate = function (vector3) {
  18798. this.computeWorldMatrix(true);
  18799. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18800. return this;
  18801. };
  18802. /**
  18803. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18804. * @param targetPoint the position (must be in same space as current mesh) to look at
  18805. * @param yawCor optional yaw (y-axis) correction in radians
  18806. * @param pitchCor optional pitch (x-axis) correction in radians
  18807. * @param rollCor optional roll (z-axis) correction in radians
  18808. * @param space the choosen space of the target
  18809. * @returns the TransformNode.
  18810. */
  18811. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18812. if (yawCor === void 0) { yawCor = 0; }
  18813. if (pitchCor === void 0) { pitchCor = 0; }
  18814. if (rollCor === void 0) { rollCor = 0; }
  18815. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18816. var dv = TransformNode._lookAtVectorCache;
  18817. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18818. targetPoint.subtractToRef(pos, dv);
  18819. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18820. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18821. var pitch = Math.atan2(dv.y, len);
  18822. if (this.rotationQuaternion) {
  18823. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18824. }
  18825. else {
  18826. this.rotation.x = pitch + pitchCor;
  18827. this.rotation.y = yaw + yawCor;
  18828. this.rotation.z = rollCor;
  18829. }
  18830. return this;
  18831. };
  18832. /**
  18833. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18834. * This Vector3 is expressed in the World space.
  18835. */
  18836. TransformNode.prototype.getDirection = function (localAxis) {
  18837. var result = BABYLON.Vector3.Zero();
  18838. this.getDirectionToRef(localAxis, result);
  18839. return result;
  18840. };
  18841. /**
  18842. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18843. * localAxis is expressed in the mesh local space.
  18844. * result is computed in the Wordl space from the mesh World matrix.
  18845. * Returns the TransformNode.
  18846. */
  18847. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18848. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18849. return this;
  18850. };
  18851. /**
  18852. * Sets a new pivot point to the current node
  18853. * @param point defines the new pivot point to use
  18854. * @param space defines if the point is in world or local space (local by default)
  18855. * @returns the current TransformNode
  18856. */
  18857. TransformNode.prototype.setPivotPoint = function (point, space) {
  18858. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18859. if (this.getScene().getRenderId() == 0) {
  18860. this.computeWorldMatrix(true);
  18861. }
  18862. var wm = this.getWorldMatrix();
  18863. if (space == BABYLON.Space.WORLD) {
  18864. var tmat = BABYLON.Tmp.Matrix[0];
  18865. wm.invertToRef(tmat);
  18866. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18867. }
  18868. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18869. };
  18870. /**
  18871. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18872. */
  18873. TransformNode.prototype.getPivotPoint = function () {
  18874. var point = BABYLON.Vector3.Zero();
  18875. this.getPivotPointToRef(point);
  18876. return point;
  18877. };
  18878. /**
  18879. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18880. * Returns the TransformNode.
  18881. */
  18882. TransformNode.prototype.getPivotPointToRef = function (result) {
  18883. result.x = -this._pivotMatrix.m[12];
  18884. result.y = -this._pivotMatrix.m[13];
  18885. result.z = -this._pivotMatrix.m[14];
  18886. return this;
  18887. };
  18888. /**
  18889. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18890. */
  18891. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18892. var point = BABYLON.Vector3.Zero();
  18893. this.getAbsolutePivotPointToRef(point);
  18894. return point;
  18895. };
  18896. /**
  18897. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18898. * Returns the TransformNode.
  18899. */
  18900. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18901. result.x = this._pivotMatrix.m[12];
  18902. result.y = this._pivotMatrix.m[13];
  18903. result.z = this._pivotMatrix.m[14];
  18904. this.getPivotPointToRef(result);
  18905. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18906. return this;
  18907. };
  18908. /**
  18909. * Defines the passed node as the parent of the current node.
  18910. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18911. * Returns the TransformNode.
  18912. */
  18913. TransformNode.prototype.setParent = function (node) {
  18914. if (node === null) {
  18915. var rotation = BABYLON.Tmp.Quaternion[0];
  18916. var position = BABYLON.Tmp.Vector3[0];
  18917. var scale = BABYLON.Tmp.Vector3[1];
  18918. if (this.parent && this.parent.computeWorldMatrix) {
  18919. this.parent.computeWorldMatrix(true);
  18920. }
  18921. this.computeWorldMatrix(true);
  18922. this.getWorldMatrix().decompose(scale, rotation, position);
  18923. if (this.rotationQuaternion) {
  18924. this.rotationQuaternion.copyFrom(rotation);
  18925. }
  18926. else {
  18927. rotation.toEulerAnglesToRef(this.rotation);
  18928. }
  18929. this.scaling.x = scale.x;
  18930. this.scaling.y = scale.y;
  18931. this.scaling.z = scale.z;
  18932. this.position.x = position.x;
  18933. this.position.y = position.y;
  18934. this.position.z = position.z;
  18935. }
  18936. else {
  18937. var rotation = BABYLON.Tmp.Quaternion[0];
  18938. var position = BABYLON.Tmp.Vector3[0];
  18939. var scale = BABYLON.Tmp.Vector3[1];
  18940. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18941. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18942. this.computeWorldMatrix(true);
  18943. node.computeWorldMatrix(true);
  18944. node.getWorldMatrix().invertToRef(invParentMatrix);
  18945. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18946. diffMatrix.decompose(scale, rotation, position);
  18947. if (this.rotationQuaternion) {
  18948. this.rotationQuaternion.copyFrom(rotation);
  18949. }
  18950. else {
  18951. rotation.toEulerAnglesToRef(this.rotation);
  18952. }
  18953. this.position.x = position.x;
  18954. this.position.y = position.y;
  18955. this.position.z = position.z;
  18956. this.scaling.x = scale.x;
  18957. this.scaling.y = scale.y;
  18958. this.scaling.z = scale.z;
  18959. }
  18960. this.parent = node;
  18961. return this;
  18962. };
  18963. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18964. get: function () {
  18965. return this._nonUniformScaling;
  18966. },
  18967. enumerable: true,
  18968. configurable: true
  18969. });
  18970. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18971. if (this._nonUniformScaling === value) {
  18972. return false;
  18973. }
  18974. this._nonUniformScaling = value;
  18975. return true;
  18976. };
  18977. /**
  18978. * Attach the current TransformNode to another TransformNode associated with a bone
  18979. * @param bone Bone affecting the TransformNode
  18980. * @param affectedTransformNode TransformNode associated with the bone
  18981. */
  18982. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18983. this._transformToBoneReferal = affectedTransformNode;
  18984. this.parent = bone;
  18985. if (bone.getWorldMatrix().determinant() < 0) {
  18986. this.scalingDeterminant *= -1;
  18987. }
  18988. return this;
  18989. };
  18990. TransformNode.prototype.detachFromBone = function () {
  18991. if (!this.parent) {
  18992. return this;
  18993. }
  18994. if (this.parent.getWorldMatrix().determinant() < 0) {
  18995. this.scalingDeterminant *= -1;
  18996. }
  18997. this._transformToBoneReferal = null;
  18998. this.parent = null;
  18999. return this;
  19000. };
  19001. /**
  19002. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19003. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19004. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19005. * The passed axis is also normalized.
  19006. * Returns the TransformNode.
  19007. */
  19008. TransformNode.prototype.rotate = function (axis, amount, space) {
  19009. axis.normalize();
  19010. if (!this.rotationQuaternion) {
  19011. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19012. this.rotation = BABYLON.Vector3.Zero();
  19013. }
  19014. var rotationQuaternion;
  19015. if (!space || space === BABYLON.Space.LOCAL) {
  19016. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19017. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19018. }
  19019. else {
  19020. if (this.parent) {
  19021. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19022. invertParentWorldMatrix.invert();
  19023. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19024. }
  19025. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19026. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19027. }
  19028. return this;
  19029. };
  19030. /**
  19031. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19032. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19033. * The passed axis is also normalized.
  19034. * Returns the TransformNode.
  19035. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19036. */
  19037. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19038. axis.normalize();
  19039. if (!this.rotationQuaternion) {
  19040. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19041. this.rotation.copyFromFloats(0, 0, 0);
  19042. }
  19043. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19044. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19045. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19046. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19047. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19048. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19049. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19050. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19051. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19052. return this;
  19053. };
  19054. /**
  19055. * Translates the mesh along the axis vector for the passed distance in the given space.
  19056. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19057. * Returns the TransformNode.
  19058. */
  19059. TransformNode.prototype.translate = function (axis, distance, space) {
  19060. var displacementVector = axis.scale(distance);
  19061. if (!space || space === BABYLON.Space.LOCAL) {
  19062. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19063. this.setPositionWithLocalVector(tempV3);
  19064. }
  19065. else {
  19066. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19067. }
  19068. return this;
  19069. };
  19070. /**
  19071. * Adds a rotation step to the mesh current rotation.
  19072. * x, y, z are Euler angles expressed in radians.
  19073. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19074. * This means this rotation is made in the mesh local space only.
  19075. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19076. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19077. * ```javascript
  19078. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19079. * ```
  19080. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19081. * 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.
  19082. * Returns the TransformNode.
  19083. */
  19084. TransformNode.prototype.addRotation = function (x, y, z) {
  19085. var rotationQuaternion;
  19086. if (this.rotationQuaternion) {
  19087. rotationQuaternion = this.rotationQuaternion;
  19088. }
  19089. else {
  19090. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19091. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19092. }
  19093. var accumulation = BABYLON.Tmp.Quaternion[0];
  19094. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19095. rotationQuaternion.multiplyInPlace(accumulation);
  19096. if (!this.rotationQuaternion) {
  19097. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19098. }
  19099. return this;
  19100. };
  19101. /**
  19102. * Computes the mesh World matrix and returns it.
  19103. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19104. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19105. * If the parameter `force`is set to `true`, the actual computation is done.
  19106. * Returns the mesh World Matrix.
  19107. */
  19108. TransformNode.prototype.computeWorldMatrix = function (force) {
  19109. if (this._isWorldMatrixFrozen) {
  19110. return this._worldMatrix;
  19111. }
  19112. if (!force && this.isSynchronized(true)) {
  19113. this._currentRenderId = this.getScene().getRenderId();
  19114. return this._worldMatrix;
  19115. }
  19116. this._cache.position.copyFrom(this.position);
  19117. this._cache.scaling.copyFrom(this.scaling);
  19118. this._cache.pivotMatrixUpdated = false;
  19119. this._cache.billboardMode = this.billboardMode;
  19120. this._currentRenderId = this.getScene().getRenderId();
  19121. this._childRenderId = this.getScene().getRenderId();
  19122. this._isDirty = false;
  19123. // Scaling
  19124. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19125. // Rotation
  19126. //rotate, if quaternion is set and rotation was used
  19127. if (this.rotationQuaternion) {
  19128. var len = this.rotation.length();
  19129. if (len) {
  19130. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19131. this.rotation.copyFromFloats(0, 0, 0);
  19132. }
  19133. }
  19134. if (this.rotationQuaternion) {
  19135. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19136. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19137. }
  19138. else {
  19139. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19140. this._cache.rotation.copyFrom(this.rotation);
  19141. }
  19142. // Translation
  19143. var camera = this.getScene().activeCamera;
  19144. if (this.infiniteDistance && !this.parent && camera) {
  19145. var cameraWorldMatrix = camera.getWorldMatrix();
  19146. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19147. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19148. }
  19149. else {
  19150. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19151. }
  19152. // Composing transformations
  19153. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19154. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19155. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19156. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19157. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19158. // Need to decompose each rotation here
  19159. var currentPosition = BABYLON.Tmp.Vector3[3];
  19160. if (this.parent && this.parent.getWorldMatrix) {
  19161. if (this._transformToBoneReferal) {
  19162. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19163. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19164. }
  19165. else {
  19166. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19167. }
  19168. }
  19169. else {
  19170. currentPosition.copyFrom(this.position);
  19171. }
  19172. currentPosition.subtractInPlace(camera.globalPosition);
  19173. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19174. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19175. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19176. }
  19177. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19178. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19179. }
  19180. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19181. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19182. }
  19183. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19184. }
  19185. else {
  19186. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19187. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19188. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19189. }
  19190. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19191. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19192. }
  19193. // Local world
  19194. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19195. // Parent
  19196. if (this.parent && this.parent.getWorldMatrix) {
  19197. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19198. if (this._transformToBoneReferal) {
  19199. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19200. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19201. }
  19202. else {
  19203. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19204. }
  19205. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19206. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19207. this._worldMatrix.copyFrom(this._localWorld);
  19208. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19209. }
  19210. else {
  19211. if (this._transformToBoneReferal) {
  19212. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19213. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19214. }
  19215. else {
  19216. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19217. }
  19218. }
  19219. this._markSyncedWithParent();
  19220. }
  19221. else {
  19222. this._worldMatrix.copyFrom(this._localWorld);
  19223. }
  19224. // Post multiply inverse of pivotMatrix
  19225. if (this._postMultiplyPivotMatrix) {
  19226. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19227. }
  19228. // Normal matrix
  19229. if (!this.ignoreNonUniformScaling) {
  19230. if (this.scaling.isNonUniform) {
  19231. this._updateNonUniformScalingState(true);
  19232. }
  19233. else if (this.parent && this.parent._nonUniformScaling) {
  19234. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19235. }
  19236. else {
  19237. this._updateNonUniformScalingState(false);
  19238. }
  19239. }
  19240. else {
  19241. this._updateNonUniformScalingState(false);
  19242. }
  19243. this._afterComputeWorldMatrix();
  19244. // Absolute position
  19245. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19246. // Callbacks
  19247. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19248. if (!this._poseMatrix) {
  19249. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19250. }
  19251. // Cache the determinant
  19252. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19253. return this._worldMatrix;
  19254. };
  19255. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19256. };
  19257. /**
  19258. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19259. * @param func: callback function to add
  19260. *
  19261. * Returns the TransformNode.
  19262. */
  19263. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19264. this.onAfterWorldMatrixUpdateObservable.add(func);
  19265. return this;
  19266. };
  19267. /**
  19268. * Removes a registered callback function.
  19269. * Returns the TransformNode.
  19270. */
  19271. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19272. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19273. return this;
  19274. };
  19275. /**
  19276. * Clone the current transform node
  19277. * Returns the new transform node
  19278. * @param name Name of the new clone
  19279. * @param newParent New parent for the clone
  19280. * @param doNotCloneChildren Do not clone children hierarchy
  19281. */
  19282. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19283. var _this = this;
  19284. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19285. result.name = name;
  19286. result.id = name;
  19287. if (newParent) {
  19288. result.parent = newParent;
  19289. }
  19290. if (!doNotCloneChildren) {
  19291. // Children
  19292. var directDescendants = this.getDescendants(true);
  19293. for (var index = 0; index < directDescendants.length; index++) {
  19294. var child = directDescendants[index];
  19295. if (child.clone) {
  19296. child.clone(name + "." + child.name, result);
  19297. }
  19298. }
  19299. }
  19300. return result;
  19301. };
  19302. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19303. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19304. serializationObject.type = this.getClassName();
  19305. // Parent
  19306. if (this.parent) {
  19307. serializationObject.parentId = this.parent.id;
  19308. }
  19309. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19310. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19311. }
  19312. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19313. serializationObject.isEnabled = this.isEnabled();
  19314. // Parent
  19315. if (this.parent) {
  19316. serializationObject.parentId = this.parent.id;
  19317. }
  19318. return serializationObject;
  19319. };
  19320. // Statics
  19321. /**
  19322. * Returns a new TransformNode object parsed from the source provided.
  19323. * The parameter `parsedMesh` is the source.
  19324. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19325. */
  19326. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19327. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19328. if (BABYLON.Tags) {
  19329. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19330. }
  19331. if (parsedTransformNode.localMatrix) {
  19332. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19333. }
  19334. else if (parsedTransformNode.pivotMatrix) {
  19335. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19336. }
  19337. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19338. // Parent
  19339. if (parsedTransformNode.parentId) {
  19340. transformNode._waitingParentId = parsedTransformNode.parentId;
  19341. }
  19342. return transformNode;
  19343. };
  19344. /**
  19345. * Releases resources associated with this transform node.
  19346. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19347. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19348. */
  19349. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19350. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19351. // Animations
  19352. this.getScene().stopAnimation(this);
  19353. // Remove from scene
  19354. this.getScene().removeTransformNode(this);
  19355. this.onAfterWorldMatrixUpdateObservable.clear();
  19356. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19357. };
  19358. // Statics
  19359. TransformNode.BILLBOARDMODE_NONE = 0;
  19360. TransformNode.BILLBOARDMODE_X = 1;
  19361. TransformNode.BILLBOARDMODE_Y = 2;
  19362. TransformNode.BILLBOARDMODE_Z = 4;
  19363. TransformNode.BILLBOARDMODE_ALL = 7;
  19364. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19365. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19366. __decorate([
  19367. BABYLON.serializeAsVector3()
  19368. ], TransformNode.prototype, "_rotation", void 0);
  19369. __decorate([
  19370. BABYLON.serializeAsQuaternion()
  19371. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19372. __decorate([
  19373. BABYLON.serializeAsVector3()
  19374. ], TransformNode.prototype, "_scaling", void 0);
  19375. __decorate([
  19376. BABYLON.serialize()
  19377. ], TransformNode.prototype, "billboardMode", void 0);
  19378. __decorate([
  19379. BABYLON.serialize()
  19380. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19381. __decorate([
  19382. BABYLON.serialize()
  19383. ], TransformNode.prototype, "infiniteDistance", void 0);
  19384. __decorate([
  19385. BABYLON.serialize()
  19386. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19387. __decorate([
  19388. BABYLON.serializeAsVector3()
  19389. ], TransformNode.prototype, "position", void 0);
  19390. return TransformNode;
  19391. }(BABYLON.Node));
  19392. BABYLON.TransformNode = TransformNode;
  19393. })(BABYLON || (BABYLON = {}));
  19394. //# sourceMappingURL=babylon.transformNode.js.map
  19395. var BABYLON;
  19396. (function (BABYLON) {
  19397. /**
  19398. * Class used to store all common mesh properties
  19399. */
  19400. var AbstractMesh = /** @class */ (function (_super) {
  19401. __extends(AbstractMesh, _super);
  19402. // Constructor
  19403. /**
  19404. * Creates a new AbstractMesh
  19405. * @param name defines the name of the mesh
  19406. * @param scene defines the hosting scene
  19407. */
  19408. function AbstractMesh(name, scene) {
  19409. if (scene === void 0) { scene = null; }
  19410. var _this = _super.call(this, name, scene, false) || this;
  19411. _this._facetNb = 0; // facet number
  19412. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19413. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19414. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19415. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19416. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19417. _this._subDiv = {
  19418. max: 1,
  19419. X: 1,
  19420. Y: 1,
  19421. Z: 1
  19422. };
  19423. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19424. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19425. // Events
  19426. /**
  19427. * An event triggered when this mesh collides with another one
  19428. */
  19429. _this.onCollideObservable = new BABYLON.Observable();
  19430. /**
  19431. * An event triggered when the collision's position changes
  19432. */
  19433. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19434. /**
  19435. * An event triggered when material is changed
  19436. */
  19437. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19438. // Properties
  19439. /**
  19440. * Gets or sets the orientation for POV movement & rotation
  19441. */
  19442. _this.definedFacingForward = true;
  19443. /**
  19444. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19445. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19446. * * 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.
  19447. * @see http://doc.babylonjs.com/features/occlusionquery
  19448. */
  19449. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19450. /**
  19451. * 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:
  19452. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19453. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19454. * * 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.
  19455. * @see http://doc.babylonjs.com/features/occlusionquery
  19456. */
  19457. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19458. /**
  19459. * 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.
  19460. * The default value is -1 which means don't break the query and wait till the result
  19461. * @see http://doc.babylonjs.com/features/occlusionquery
  19462. */
  19463. _this.occlusionRetryCount = -1;
  19464. _this._occlusionInternalRetryCounter = 0;
  19465. _this._isOccluded = false;
  19466. _this._isOcclusionQueryInProgress = false;
  19467. _this._visibility = 1.0;
  19468. /** Gets or sets the alpha index used to sort transparent meshes
  19469. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19470. */
  19471. _this.alphaIndex = Number.MAX_VALUE;
  19472. /**
  19473. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19474. */
  19475. _this.isVisible = true;
  19476. /**
  19477. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19478. */
  19479. _this.isPickable = true;
  19480. /**
  19481. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19482. */
  19483. _this.showBoundingBox = false;
  19484. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19485. _this.showSubMeshesBoundingBox = false;
  19486. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19487. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19488. */
  19489. _this.isBlocker = false;
  19490. /**
  19491. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19492. */
  19493. _this.enablePointerMoveEvents = false;
  19494. /**
  19495. * Specifies the rendering group id for this mesh (0 by default)
  19496. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19497. */
  19498. _this.renderingGroupId = 0;
  19499. _this._receiveShadows = false;
  19500. /**
  19501. * Gets or sets a boolean indicating if the outline must be rendered as well
  19502. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19503. */
  19504. _this.renderOutline = false;
  19505. /** Defines color to use when rendering outline */
  19506. _this.outlineColor = BABYLON.Color3.Red();
  19507. /** Define width to use when rendering outline */
  19508. _this.outlineWidth = 0.02;
  19509. /**
  19510. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19511. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19512. */
  19513. _this.renderOverlay = false;
  19514. /** Defines color to use when rendering overlay */
  19515. _this.overlayColor = BABYLON.Color3.Red();
  19516. /** Defines alpha to use when rendering overlay */
  19517. _this.overlayAlpha = 0.5;
  19518. _this._hasVertexAlpha = false;
  19519. _this._useVertexColors = true;
  19520. _this._computeBonesUsingShaders = true;
  19521. _this._numBoneInfluencers = 4;
  19522. _this._applyFog = true;
  19523. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19524. _this.useOctreeForRenderingSelection = true;
  19525. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19526. _this.useOctreeForPicking = true;
  19527. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19528. _this.useOctreeForCollisions = true;
  19529. _this._layerMask = 0x0FFFFFFF;
  19530. /**
  19531. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19532. */
  19533. _this.alwaysSelectAsActiveMesh = false;
  19534. /**
  19535. * Gets or sets the current action manager
  19536. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19537. */
  19538. _this.actionManager = null;
  19539. /**
  19540. * Gets or sets impostor used for physic simulation
  19541. * @see http://doc.babylonjs.com/features/physics_engine
  19542. */
  19543. _this.physicsImpostor = null;
  19544. // Collisions
  19545. _this._checkCollisions = false;
  19546. _this._collisionMask = -1;
  19547. _this._collisionGroup = -1;
  19548. /**
  19549. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19550. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19551. */
  19552. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19553. /**
  19554. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19555. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19556. */
  19557. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19558. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19559. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19560. // Edges
  19561. /**
  19562. * Defines edge width used when edgesRenderer is enabled
  19563. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19564. */
  19565. _this.edgesWidth = 1;
  19566. /**
  19567. * Defines edge color used when edgesRenderer is enabled
  19568. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19569. */
  19570. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19571. // Cache
  19572. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19573. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19574. /** @hidden */
  19575. _this._renderId = 0;
  19576. /** @hidden */
  19577. _this._intersectionsInProgress = new Array();
  19578. /** @hidden */
  19579. _this._unIndexed = false;
  19580. /** @hidden */
  19581. _this._lightSources = new Array();
  19582. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19583. if (collidedMesh === void 0) { collidedMesh = null; }
  19584. //TODO move this to the collision coordinator!
  19585. if (_this.getScene().workerCollisions)
  19586. newPosition.multiplyInPlace(_this._collider._radius);
  19587. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19588. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19589. _this.position.addInPlace(_this._diffPositionForCollisions);
  19590. }
  19591. if (collidedMesh) {
  19592. _this.onCollideObservable.notifyObservers(collidedMesh);
  19593. }
  19594. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19595. };
  19596. _this.getScene().addMesh(_this);
  19597. _this._resyncLightSources();
  19598. return _this;
  19599. }
  19600. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19601. /**
  19602. * No billboard
  19603. */
  19604. get: function () {
  19605. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19606. },
  19607. enumerable: true,
  19608. configurable: true
  19609. });
  19610. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19611. /** Billboard on X axis */
  19612. get: function () {
  19613. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19614. },
  19615. enumerable: true,
  19616. configurable: true
  19617. });
  19618. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19619. /** Billboard on Y axis */
  19620. get: function () {
  19621. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19622. },
  19623. enumerable: true,
  19624. configurable: true
  19625. });
  19626. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19627. /** Billboard on Z axis */
  19628. get: function () {
  19629. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19630. },
  19631. enumerable: true,
  19632. configurable: true
  19633. });
  19634. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19635. /** Billboard on all axes */
  19636. get: function () {
  19637. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19638. },
  19639. enumerable: true,
  19640. configurable: true
  19641. });
  19642. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19643. /**
  19644. * Gets the number of facets in the mesh
  19645. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19646. */
  19647. get: function () {
  19648. return this._facetNb;
  19649. },
  19650. enumerable: true,
  19651. configurable: true
  19652. });
  19653. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19654. /**
  19655. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19656. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19657. */
  19658. get: function () {
  19659. return this._partitioningSubdivisions;
  19660. },
  19661. set: function (nb) {
  19662. this._partitioningSubdivisions = nb;
  19663. },
  19664. enumerable: true,
  19665. configurable: true
  19666. });
  19667. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19668. /**
  19669. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19670. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19671. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19672. */
  19673. get: function () {
  19674. return this._partitioningBBoxRatio;
  19675. },
  19676. set: function (ratio) {
  19677. this._partitioningBBoxRatio = ratio;
  19678. },
  19679. enumerable: true,
  19680. configurable: true
  19681. });
  19682. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19683. /**
  19684. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19685. * Works only for updatable meshes.
  19686. * Doesn't work with multi-materials
  19687. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19688. */
  19689. get: function () {
  19690. return this._facetDepthSort;
  19691. },
  19692. set: function (sort) {
  19693. this._facetDepthSort = sort;
  19694. },
  19695. enumerable: true,
  19696. configurable: true
  19697. });
  19698. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19699. /**
  19700. * The location (Vector3) where the facet depth sort must be computed from.
  19701. * By default, the active camera position.
  19702. * Used only when facet depth sort is enabled
  19703. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19704. */
  19705. get: function () {
  19706. return this._facetDepthSortFrom;
  19707. },
  19708. set: function (location) {
  19709. this._facetDepthSortFrom = location;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19715. /**
  19716. * gets a boolean indicating if facetData is enabled
  19717. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19718. */
  19719. get: function () {
  19720. return this._facetDataEnabled;
  19721. },
  19722. enumerable: true,
  19723. configurable: true
  19724. });
  19725. /** @hidden */
  19726. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19727. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19728. return false;
  19729. }
  19730. this._markSubMeshesAsMiscDirty();
  19731. return true;
  19732. };
  19733. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19734. /** Set a function to call when this mesh collides with another one */
  19735. set: function (callback) {
  19736. if (this._onCollideObserver) {
  19737. this.onCollideObservable.remove(this._onCollideObserver);
  19738. }
  19739. this._onCollideObserver = this.onCollideObservable.add(callback);
  19740. },
  19741. enumerable: true,
  19742. configurable: true
  19743. });
  19744. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19745. /** Set a function to call when the collision's position changes */
  19746. set: function (callback) {
  19747. if (this._onCollisionPositionChangeObserver) {
  19748. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19749. }
  19750. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19756. /**
  19757. * 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
  19758. * @see http://doc.babylonjs.com/features/occlusionquery
  19759. */
  19760. get: function () {
  19761. return this._isOccluded;
  19762. },
  19763. set: function (value) {
  19764. this._isOccluded = value;
  19765. },
  19766. enumerable: true,
  19767. configurable: true
  19768. });
  19769. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19770. /**
  19771. * Flag to check the progress status of the query
  19772. * @see http://doc.babylonjs.com/features/occlusionquery
  19773. */
  19774. get: function () {
  19775. return this._isOcclusionQueryInProgress;
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19781. /**
  19782. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19783. */
  19784. get: function () {
  19785. return this._visibility;
  19786. },
  19787. /**
  19788. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19789. */
  19790. set: function (value) {
  19791. if (this._visibility === value) {
  19792. return;
  19793. }
  19794. this._visibility = value;
  19795. this._markSubMeshesAsMiscDirty();
  19796. },
  19797. enumerable: true,
  19798. configurable: true
  19799. });
  19800. Object.defineProperty(AbstractMesh.prototype, "material", {
  19801. /** Gets or sets current material */
  19802. get: function () {
  19803. return this._material;
  19804. },
  19805. set: function (value) {
  19806. if (this._material === value) {
  19807. return;
  19808. }
  19809. this._material = value;
  19810. if (this.onMaterialChangedObservable.hasObservers) {
  19811. this.onMaterialChangedObservable.notifyObservers(this);
  19812. }
  19813. if (!this.subMeshes) {
  19814. return;
  19815. }
  19816. this._unBindEffect();
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19822. /**
  19823. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19824. * @see http://doc.babylonjs.com/babylon101/shadows
  19825. */
  19826. get: function () {
  19827. return this._receiveShadows;
  19828. },
  19829. set: function (value) {
  19830. if (this._receiveShadows === value) {
  19831. return;
  19832. }
  19833. this._receiveShadows = value;
  19834. this._markSubMeshesAsLightDirty();
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19840. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19841. get: function () {
  19842. return this._hasVertexAlpha;
  19843. },
  19844. set: function (value) {
  19845. if (this._hasVertexAlpha === value) {
  19846. return;
  19847. }
  19848. this._hasVertexAlpha = value;
  19849. this._markSubMeshesAsAttributesDirty();
  19850. this._markSubMeshesAsMiscDirty();
  19851. },
  19852. enumerable: true,
  19853. configurable: true
  19854. });
  19855. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19856. /** 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) */
  19857. get: function () {
  19858. return this._useVertexColors;
  19859. },
  19860. set: function (value) {
  19861. if (this._useVertexColors === value) {
  19862. return;
  19863. }
  19864. this._useVertexColors = value;
  19865. this._markSubMeshesAsAttributesDirty();
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19871. /**
  19872. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19873. */
  19874. get: function () {
  19875. return this._computeBonesUsingShaders;
  19876. },
  19877. set: function (value) {
  19878. if (this._computeBonesUsingShaders === value) {
  19879. return;
  19880. }
  19881. this._computeBonesUsingShaders = value;
  19882. this._markSubMeshesAsAttributesDirty();
  19883. },
  19884. enumerable: true,
  19885. configurable: true
  19886. });
  19887. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19888. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19889. get: function () {
  19890. return this._numBoneInfluencers;
  19891. },
  19892. set: function (value) {
  19893. if (this._numBoneInfluencers === value) {
  19894. return;
  19895. }
  19896. this._numBoneInfluencers = value;
  19897. this._markSubMeshesAsAttributesDirty();
  19898. },
  19899. enumerable: true,
  19900. configurable: true
  19901. });
  19902. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19903. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19904. get: function () {
  19905. return this._applyFog;
  19906. },
  19907. set: function (value) {
  19908. if (this._applyFog === value) {
  19909. return;
  19910. }
  19911. this._applyFog = value;
  19912. this._markSubMeshesAsMiscDirty();
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19918. /**
  19919. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19920. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19921. */
  19922. get: function () {
  19923. return this._layerMask;
  19924. },
  19925. set: function (value) {
  19926. if (value === this._layerMask) {
  19927. return;
  19928. }
  19929. this._layerMask = value;
  19930. this._resyncLightSources();
  19931. },
  19932. enumerable: true,
  19933. configurable: true
  19934. });
  19935. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19936. /**
  19937. * Gets or sets a collision mask used to mask collisions (default is -1).
  19938. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19939. */
  19940. get: function () {
  19941. return this._collisionMask;
  19942. },
  19943. set: function (mask) {
  19944. this._collisionMask = !isNaN(mask) ? mask : -1;
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19950. /**
  19951. * Gets or sets the current collision group mask (-1 by default).
  19952. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19953. */
  19954. get: function () {
  19955. return this._collisionGroup;
  19956. },
  19957. set: function (mask) {
  19958. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19959. },
  19960. enumerable: true,
  19961. configurable: true
  19962. });
  19963. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19964. /** @hidden */
  19965. get: function () {
  19966. return null;
  19967. },
  19968. enumerable: true,
  19969. configurable: true
  19970. });
  19971. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19972. get: function () {
  19973. return this._skeleton;
  19974. },
  19975. /**
  19976. * Gets or sets a skeleton to apply skining transformations
  19977. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19978. */
  19979. set: function (value) {
  19980. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19981. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19982. }
  19983. if (value && value.needInitialSkinMatrix) {
  19984. value._registerMeshWithPoseMatrix(this);
  19985. }
  19986. this._skeleton = value;
  19987. if (!this._skeleton) {
  19988. this._bonesTransformMatrices = null;
  19989. }
  19990. this._markSubMeshesAsAttributesDirty();
  19991. },
  19992. enumerable: true,
  19993. configurable: true
  19994. });
  19995. /**
  19996. * Returns the string "AbstractMesh"
  19997. * @returns "AbstractMesh"
  19998. */
  19999. AbstractMesh.prototype.getClassName = function () {
  20000. return "AbstractMesh";
  20001. };
  20002. /**
  20003. * Gets a string representation of the current mesh
  20004. * @param fullDetails defines a boolean indicating if full details must be included
  20005. * @returns a string representation of the current mesh
  20006. */
  20007. AbstractMesh.prototype.toString = function (fullDetails) {
  20008. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20009. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20010. if (this._skeleton) {
  20011. ret += ", skeleton: " + this._skeleton.name;
  20012. }
  20013. if (fullDetails) {
  20014. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20015. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20016. }
  20017. return ret;
  20018. };
  20019. /** @hidden */
  20020. AbstractMesh.prototype._rebuild = function () {
  20021. if (this._occlusionQuery) {
  20022. this._occlusionQuery = null;
  20023. }
  20024. if (this._edgesRenderer) {
  20025. this._edgesRenderer._rebuild();
  20026. }
  20027. if (!this.subMeshes) {
  20028. return;
  20029. }
  20030. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20031. var subMesh = _a[_i];
  20032. subMesh._rebuild();
  20033. }
  20034. };
  20035. /** @hidden */
  20036. AbstractMesh.prototype._resyncLightSources = function () {
  20037. this._lightSources.length = 0;
  20038. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20039. var light = _a[_i];
  20040. if (!light.isEnabled()) {
  20041. continue;
  20042. }
  20043. if (light.canAffectMesh(this)) {
  20044. this._lightSources.push(light);
  20045. }
  20046. }
  20047. this._markSubMeshesAsLightDirty();
  20048. };
  20049. /** @hidden */
  20050. AbstractMesh.prototype._resyncLighSource = function (light) {
  20051. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20052. var index = this._lightSources.indexOf(light);
  20053. if (index === -1) {
  20054. if (!isIn) {
  20055. return;
  20056. }
  20057. this._lightSources.push(light);
  20058. }
  20059. else {
  20060. if (isIn) {
  20061. return;
  20062. }
  20063. this._lightSources.splice(index, 1);
  20064. }
  20065. this._markSubMeshesAsLightDirty();
  20066. };
  20067. /** @hidden */
  20068. AbstractMesh.prototype._unBindEffect = function () {
  20069. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20070. var subMesh = _a[_i];
  20071. subMesh.setEffect(null);
  20072. }
  20073. };
  20074. /** @hidden */
  20075. AbstractMesh.prototype._removeLightSource = function (light) {
  20076. var index = this._lightSources.indexOf(light);
  20077. if (index === -1) {
  20078. return;
  20079. }
  20080. this._lightSources.splice(index, 1);
  20081. this._markSubMeshesAsLightDirty();
  20082. };
  20083. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20084. if (!this.subMeshes) {
  20085. return;
  20086. }
  20087. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20088. var subMesh = _a[_i];
  20089. if (subMesh._materialDefines) {
  20090. func(subMesh._materialDefines);
  20091. }
  20092. }
  20093. };
  20094. /** @hidden */
  20095. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20096. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20097. };
  20098. /** @hidden */
  20099. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20100. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20101. };
  20102. /** @hidden */
  20103. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20104. if (!this.subMeshes) {
  20105. return;
  20106. }
  20107. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20108. var subMesh = _a[_i];
  20109. var material = subMesh.getMaterial();
  20110. if (material) {
  20111. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20112. }
  20113. }
  20114. };
  20115. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20116. /**
  20117. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20118. */
  20119. get: function () {
  20120. return this._scaling;
  20121. },
  20122. set: function (newScaling) {
  20123. this._scaling = newScaling;
  20124. if (this.physicsImpostor) {
  20125. this.physicsImpostor.forceUpdate();
  20126. }
  20127. },
  20128. enumerable: true,
  20129. configurable: true
  20130. });
  20131. // Methods
  20132. /**
  20133. * Disables the mesh edge rendering mode
  20134. * @returns the currentAbstractMesh
  20135. */
  20136. AbstractMesh.prototype.disableEdgesRendering = function () {
  20137. if (this._edgesRenderer) {
  20138. this._edgesRenderer.dispose();
  20139. this._edgesRenderer = null;
  20140. }
  20141. return this;
  20142. };
  20143. /**
  20144. * Enables the edge rendering mode on the mesh.
  20145. * This mode makes the mesh edges visible
  20146. * @param epsilon defines the maximal distance between two angles to detect a face
  20147. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20148. * @returns the currentAbstractMesh
  20149. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20150. */
  20151. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20152. if (epsilon === void 0) { epsilon = 0.95; }
  20153. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20154. this.disableEdgesRendering();
  20155. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20156. return this;
  20157. };
  20158. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20159. /**
  20160. * Gets the edgesRenderer associated with the mesh
  20161. */
  20162. get: function () {
  20163. return this._edgesRenderer;
  20164. },
  20165. enumerable: true,
  20166. configurable: true
  20167. });
  20168. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20169. /**
  20170. * Returns true if the mesh is blocked. Implemented by child classes
  20171. */
  20172. get: function () {
  20173. return false;
  20174. },
  20175. enumerable: true,
  20176. configurable: true
  20177. });
  20178. /**
  20179. * Returns the mesh itself by default. Implemented by child classes
  20180. * @param camera defines the camera to use to pick the right LOD level
  20181. * @returns the currentAbstractMesh
  20182. */
  20183. AbstractMesh.prototype.getLOD = function (camera) {
  20184. return this;
  20185. };
  20186. /**
  20187. * Returns 0 by default. Implemented by child classes
  20188. * @returns an integer
  20189. */
  20190. AbstractMesh.prototype.getTotalVertices = function () {
  20191. return 0;
  20192. };
  20193. /**
  20194. * Returns null by default. Implemented by child classes
  20195. * @returns null
  20196. */
  20197. AbstractMesh.prototype.getIndices = function () {
  20198. return null;
  20199. };
  20200. /**
  20201. * Returns the array of the requested vertex data kind. Implemented by child classes
  20202. * @param kind defines the vertex data kind to use
  20203. * @returns null
  20204. */
  20205. AbstractMesh.prototype.getVerticesData = function (kind) {
  20206. return null;
  20207. };
  20208. /**
  20209. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20210. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20211. * Note that a new underlying VertexBuffer object is created each call.
  20212. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20213. * @param kind defines vertex data kind:
  20214. * * BABYLON.VertexBuffer.PositionKind
  20215. * * BABYLON.VertexBuffer.UVKind
  20216. * * BABYLON.VertexBuffer.UV2Kind
  20217. * * BABYLON.VertexBuffer.UV3Kind
  20218. * * BABYLON.VertexBuffer.UV4Kind
  20219. * * BABYLON.VertexBuffer.UV5Kind
  20220. * * BABYLON.VertexBuffer.UV6Kind
  20221. * * BABYLON.VertexBuffer.ColorKind
  20222. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20223. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20224. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20225. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20226. * @param data defines the data source
  20227. * @param updatable defines if the data must be flagged as updatable (or static)
  20228. * @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
  20229. * @returns the current mesh
  20230. */
  20231. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20232. return this;
  20233. };
  20234. /**
  20235. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20236. * If the mesh has no geometry, it is simply returned as it is.
  20237. * @param kind defines vertex data kind:
  20238. * * BABYLON.VertexBuffer.PositionKind
  20239. * * BABYLON.VertexBuffer.UVKind
  20240. * * BABYLON.VertexBuffer.UV2Kind
  20241. * * BABYLON.VertexBuffer.UV3Kind
  20242. * * BABYLON.VertexBuffer.UV4Kind
  20243. * * BABYLON.VertexBuffer.UV5Kind
  20244. * * BABYLON.VertexBuffer.UV6Kind
  20245. * * BABYLON.VertexBuffer.ColorKind
  20246. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20247. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20248. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20249. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20250. * @param data defines the data source
  20251. * @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
  20252. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20253. * @returns the current mesh
  20254. */
  20255. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20256. return this;
  20257. };
  20258. /**
  20259. * Sets the mesh indices,
  20260. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20261. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20262. * @param totalVertices Defines the total number of vertices
  20263. * @returns the current mesh
  20264. */
  20265. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20266. return this;
  20267. };
  20268. /**
  20269. * Gets a boolean indicating if specific vertex data is present
  20270. * @param kind defines the vertex data kind to use
  20271. * @returns true is data kind is present
  20272. */
  20273. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20274. return false;
  20275. };
  20276. /**
  20277. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20278. * @returns a BoundingInfo
  20279. */
  20280. AbstractMesh.prototype.getBoundingInfo = function () {
  20281. if (this._masterMesh) {
  20282. return this._masterMesh.getBoundingInfo();
  20283. }
  20284. if (!this._boundingInfo) {
  20285. // this._boundingInfo is being created here
  20286. this._updateBoundingInfo();
  20287. }
  20288. // cannot be null.
  20289. return this._boundingInfo;
  20290. };
  20291. /**
  20292. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20293. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20294. * @returns the current mesh
  20295. */
  20296. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20297. if (includeDescendants === void 0) { includeDescendants = true; }
  20298. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20299. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20300. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20301. if (maxDimension === 0) {
  20302. return this;
  20303. }
  20304. var scale = 1 / maxDimension;
  20305. this.scaling.scaleInPlace(scale);
  20306. return this;
  20307. };
  20308. /**
  20309. * Overwrite the current bounding info
  20310. * @param boundingInfo defines the new bounding info
  20311. * @returns the current mesh
  20312. */
  20313. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20314. this._boundingInfo = boundingInfo;
  20315. return this;
  20316. };
  20317. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20318. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20319. get: function () {
  20320. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20321. },
  20322. enumerable: true,
  20323. configurable: true
  20324. });
  20325. /** @hidden */
  20326. AbstractMesh.prototype._preActivate = function () {
  20327. };
  20328. /** @hidden */
  20329. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20330. };
  20331. /** @hidden */
  20332. AbstractMesh.prototype._activate = function (renderId) {
  20333. this._renderId = renderId;
  20334. };
  20335. /**
  20336. * Gets the current world matrix
  20337. * @returns a Matrix
  20338. */
  20339. AbstractMesh.prototype.getWorldMatrix = function () {
  20340. if (this._masterMesh) {
  20341. return this._masterMesh.getWorldMatrix();
  20342. }
  20343. return _super.prototype.getWorldMatrix.call(this);
  20344. };
  20345. /** @hidden */
  20346. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20347. if (this._masterMesh) {
  20348. return this._masterMesh._getWorldMatrixDeterminant();
  20349. }
  20350. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20351. };
  20352. // ================================== Point of View Movement =================================
  20353. /**
  20354. * Perform relative position change from the point of view of behind the front of the mesh.
  20355. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20356. * Supports definition of mesh facing forward or backward
  20357. * @param amountRight defines the distance on the right axis
  20358. * @param amountUp defines the distance on the up axis
  20359. * @param amountForward defines the distance on the forward axis
  20360. * @returns the current mesh
  20361. */
  20362. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20363. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20364. return this;
  20365. };
  20366. /**
  20367. * Calculate relative position change from the point of view of behind the front of the mesh.
  20368. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20369. * Supports definition of mesh facing forward or backward
  20370. * @param amountRight defines the distance on the right axis
  20371. * @param amountUp defines the distance on the up axis
  20372. * @param amountForward defines the distance on the forward axis
  20373. * @returns the new displacement vector
  20374. */
  20375. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20376. var rotMatrix = new BABYLON.Matrix();
  20377. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20378. rotQuaternion.toRotationMatrix(rotMatrix);
  20379. var translationDelta = BABYLON.Vector3.Zero();
  20380. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20381. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20382. return translationDelta;
  20383. };
  20384. // ================================== Point of View Rotation =================================
  20385. /**
  20386. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20387. * Supports definition of mesh facing forward or backward
  20388. * @param flipBack defines the flip
  20389. * @param twirlClockwise defines the twirl
  20390. * @param tiltRight defines the tilt
  20391. * @returns the current mesh
  20392. */
  20393. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20394. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20395. return this;
  20396. };
  20397. /**
  20398. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20399. * Supports definition of mesh facing forward or backward.
  20400. * @param flipBack defines the flip
  20401. * @param twirlClockwise defines the twirl
  20402. * @param tiltRight defines the tilt
  20403. * @returns the new rotation vector
  20404. */
  20405. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20406. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20407. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20408. };
  20409. /**
  20410. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20411. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20412. * @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
  20413. * @returns the new bounding vectors
  20414. */
  20415. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20416. if (includeDescendants === void 0) { includeDescendants = true; }
  20417. if (predicate === void 0) { predicate = null; }
  20418. // Ensures that all world matrix will be recomputed.
  20419. this.getScene().incrementRenderId();
  20420. this.computeWorldMatrix(true);
  20421. var min;
  20422. var max;
  20423. var boundingInfo = this.getBoundingInfo();
  20424. if (!this.subMeshes) {
  20425. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20426. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20427. }
  20428. else {
  20429. min = boundingInfo.boundingBox.minimumWorld;
  20430. max = boundingInfo.boundingBox.maximumWorld;
  20431. }
  20432. if (includeDescendants) {
  20433. var descendants = this.getDescendants(false);
  20434. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20435. var descendant = descendants_1[_i];
  20436. var childMesh = descendant;
  20437. childMesh.computeWorldMatrix(true);
  20438. // Filters meshes based on custom predicate function.
  20439. if (predicate && !predicate(childMesh)) {
  20440. continue;
  20441. }
  20442. //make sure we have the needed params to get mix and max
  20443. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20444. continue;
  20445. }
  20446. var childBoundingInfo = childMesh.getBoundingInfo();
  20447. var boundingBox = childBoundingInfo.boundingBox;
  20448. var minBox = boundingBox.minimumWorld;
  20449. var maxBox = boundingBox.maximumWorld;
  20450. BABYLON.Tools.CheckExtends(minBox, min, max);
  20451. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20452. }
  20453. }
  20454. return {
  20455. min: min,
  20456. max: max
  20457. };
  20458. };
  20459. /** @hidden */
  20460. AbstractMesh.prototype._updateBoundingInfo = function () {
  20461. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20462. this._boundingInfo.update(this.worldMatrixFromCache);
  20463. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20464. return this;
  20465. };
  20466. /** @hidden */
  20467. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20468. if (!this.subMeshes) {
  20469. return this;
  20470. }
  20471. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20472. var subMesh = this.subMeshes[subIndex];
  20473. if (!subMesh.IsGlobal) {
  20474. subMesh.updateBoundingInfo(matrix);
  20475. }
  20476. }
  20477. return this;
  20478. };
  20479. /** @hidden */
  20480. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20481. // Bounding info
  20482. this._updateBoundingInfo();
  20483. };
  20484. /**
  20485. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20486. * A mesh is in the frustum if its bounding box intersects the frustum
  20487. * @param frustumPlanes defines the frustum to test
  20488. * @returns true if the mesh is in the frustum planes
  20489. */
  20490. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20491. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20492. };
  20493. /**
  20494. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20495. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20496. * @param frustumPlanes defines the frustum to test
  20497. * @returns true if the mesh is completely in the frustum planes
  20498. */
  20499. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20500. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20501. };
  20502. /**
  20503. * True if the mesh intersects another mesh or a SolidParticle object
  20504. * @param mesh defines a target mesh or SolidParticle to test
  20505. * @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)
  20506. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20507. * @returns true if there is an intersection
  20508. */
  20509. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20510. if (precise === void 0) { precise = false; }
  20511. if (!this._boundingInfo || !mesh._boundingInfo) {
  20512. return false;
  20513. }
  20514. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20515. return true;
  20516. }
  20517. if (includeDescendants) {
  20518. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20519. var child = _a[_i];
  20520. if (child.intersectsMesh(mesh, precise, true)) {
  20521. return true;
  20522. }
  20523. }
  20524. }
  20525. return false;
  20526. };
  20527. /**
  20528. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20529. * @param point defines the point to test
  20530. * @returns true if there is an intersection
  20531. */
  20532. AbstractMesh.prototype.intersectsPoint = function (point) {
  20533. if (!this._boundingInfo) {
  20534. return false;
  20535. }
  20536. return this._boundingInfo.intersectsPoint(point);
  20537. };
  20538. /**
  20539. * Gets the current physics impostor
  20540. * @see http://doc.babylonjs.com/features/physics_engine
  20541. * @returns a physics impostor or null
  20542. */
  20543. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20544. return this.physicsImpostor;
  20545. };
  20546. /**
  20547. * Gets the position of the current mesh in camera space
  20548. * @param camera defines the camera to use
  20549. * @returns a position
  20550. */
  20551. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20552. if (camera === void 0) { camera = null; }
  20553. if (!camera) {
  20554. camera = this.getScene().activeCamera;
  20555. }
  20556. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20557. };
  20558. /**
  20559. * Returns the distance from the mesh to the active camera
  20560. * @param camera defines the camera to use
  20561. * @returns the distance
  20562. */
  20563. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20564. if (camera === void 0) { camera = null; }
  20565. if (!camera) {
  20566. camera = this.getScene().activeCamera;
  20567. }
  20568. return this.absolutePosition.subtract(camera.position).length();
  20569. };
  20570. /**
  20571. * Apply a physic impulse to the mesh
  20572. * @param force defines the force to apply
  20573. * @param contactPoint defines where to apply the force
  20574. * @returns the current mesh
  20575. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20576. */
  20577. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20578. if (!this.physicsImpostor) {
  20579. return this;
  20580. }
  20581. this.physicsImpostor.applyImpulse(force, contactPoint);
  20582. return this;
  20583. };
  20584. /**
  20585. * Creates a physic joint between two meshes
  20586. * @param otherMesh defines the other mesh to use
  20587. * @param pivot1 defines the pivot to use on this mesh
  20588. * @param pivot2 defines the pivot to use on the other mesh
  20589. * @param options defines additional options (can be plugin dependent)
  20590. * @returns the current mesh
  20591. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20592. */
  20593. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20594. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20595. return this;
  20596. }
  20597. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20598. mainPivot: pivot1,
  20599. connectedPivot: pivot2,
  20600. nativeParams: options
  20601. });
  20602. return this;
  20603. };
  20604. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20605. // Collisions
  20606. /**
  20607. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20608. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20609. */
  20610. get: function () {
  20611. return this._checkCollisions;
  20612. },
  20613. set: function (collisionEnabled) {
  20614. this._checkCollisions = collisionEnabled;
  20615. if (this.getScene().workerCollisions) {
  20616. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20617. }
  20618. },
  20619. enumerable: true,
  20620. configurable: true
  20621. });
  20622. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20623. /**
  20624. * Gets Collider object used to compute collisions (not physics)
  20625. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20626. */
  20627. get: function () {
  20628. return this._collider;
  20629. },
  20630. enumerable: true,
  20631. configurable: true
  20632. });
  20633. /**
  20634. * Move the mesh using collision engine
  20635. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20636. * @param displacement defines the requested displacement vector
  20637. * @returns the current mesh
  20638. */
  20639. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20640. var globalPosition = this.getAbsolutePosition();
  20641. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20642. if (!this._collider) {
  20643. this._collider = new BABYLON.Collider();
  20644. }
  20645. this._collider._radius = this.ellipsoid;
  20646. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20647. return this;
  20648. };
  20649. // Submeshes octree
  20650. /**
  20651. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20652. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20653. * @param maxCapacity defines the maximum size of each block (64 by default)
  20654. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20655. * @returns the new octree
  20656. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20657. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20658. */
  20659. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20660. if (maxCapacity === void 0) { maxCapacity = 64; }
  20661. if (maxDepth === void 0) { maxDepth = 2; }
  20662. if (!this._submeshesOctree) {
  20663. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20664. }
  20665. this.computeWorldMatrix(true);
  20666. var boundingInfo = this.getBoundingInfo();
  20667. // Update octree
  20668. var bbox = boundingInfo.boundingBox;
  20669. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20670. return this._submeshesOctree;
  20671. };
  20672. // Collisions
  20673. /** @hidden */
  20674. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20675. this._generatePointsArray();
  20676. if (!this._positions) {
  20677. return this;
  20678. }
  20679. // Transformation
  20680. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20681. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20682. subMesh._lastColliderWorldVertices = [];
  20683. subMesh._trianglePlanes = [];
  20684. var start = subMesh.verticesStart;
  20685. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20686. for (var i = start; i < end; i++) {
  20687. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20688. }
  20689. }
  20690. // Collide
  20691. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20692. if (collider.collisionFound) {
  20693. collider.collidedMesh = this;
  20694. }
  20695. return this;
  20696. };
  20697. /** @hidden */
  20698. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20699. var subMeshes;
  20700. var len;
  20701. // Octrees
  20702. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20703. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20704. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20705. len = intersections.length;
  20706. subMeshes = intersections.data;
  20707. }
  20708. else {
  20709. subMeshes = this.subMeshes;
  20710. len = subMeshes.length;
  20711. }
  20712. for (var index = 0; index < len; index++) {
  20713. var subMesh = subMeshes[index];
  20714. // Bounding test
  20715. if (len > 1 && !subMesh._checkCollision(collider))
  20716. continue;
  20717. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20718. }
  20719. return this;
  20720. };
  20721. /** @hidden */
  20722. AbstractMesh.prototype._checkCollision = function (collider) {
  20723. // Bounding box test
  20724. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20725. return this;
  20726. // Transformation matrix
  20727. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20728. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20729. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20730. return this;
  20731. };
  20732. // Picking
  20733. /** @hidden */
  20734. AbstractMesh.prototype._generatePointsArray = function () {
  20735. return false;
  20736. };
  20737. /**
  20738. * Checks if the passed Ray intersects with the mesh
  20739. * @param ray defines the ray to use
  20740. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20741. * @returns the picking info
  20742. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20743. */
  20744. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20745. var pickingInfo = new BABYLON.PickingInfo();
  20746. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20747. return pickingInfo;
  20748. }
  20749. if (!this._generatePointsArray()) {
  20750. return pickingInfo;
  20751. }
  20752. var intersectInfo = null;
  20753. // Octrees
  20754. var subMeshes;
  20755. var len;
  20756. if (this._submeshesOctree && this.useOctreeForPicking) {
  20757. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20758. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20759. len = intersections.length;
  20760. subMeshes = intersections.data;
  20761. }
  20762. else {
  20763. subMeshes = this.subMeshes;
  20764. len = subMeshes.length;
  20765. }
  20766. for (var index = 0; index < len; index++) {
  20767. var subMesh = subMeshes[index];
  20768. // Bounding test
  20769. if (len > 1 && !subMesh.canIntersects(ray))
  20770. continue;
  20771. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20772. if (currentIntersectInfo) {
  20773. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20774. intersectInfo = currentIntersectInfo;
  20775. intersectInfo.subMeshId = index;
  20776. if (fastCheck) {
  20777. break;
  20778. }
  20779. }
  20780. }
  20781. }
  20782. if (intersectInfo) {
  20783. // Get picked point
  20784. var world = this.getWorldMatrix();
  20785. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20786. var direction = ray.direction.clone();
  20787. direction = direction.scale(intersectInfo.distance);
  20788. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20789. var pickedPoint = worldOrigin.add(worldDirection);
  20790. // Return result
  20791. pickingInfo.hit = true;
  20792. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20793. pickingInfo.pickedPoint = pickedPoint;
  20794. pickingInfo.pickedMesh = this;
  20795. pickingInfo.bu = intersectInfo.bu || 0;
  20796. pickingInfo.bv = intersectInfo.bv || 0;
  20797. pickingInfo.faceId = intersectInfo.faceId;
  20798. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20799. return pickingInfo;
  20800. }
  20801. return pickingInfo;
  20802. };
  20803. /**
  20804. * Clones the current mesh
  20805. * @param name defines the mesh name
  20806. * @param newParent defines the new mesh parent
  20807. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20808. * @returns the new mesh
  20809. */
  20810. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20811. return null;
  20812. };
  20813. /**
  20814. * Disposes all the submeshes of the current meshnp
  20815. * @returns the current mesh
  20816. */
  20817. AbstractMesh.prototype.releaseSubMeshes = function () {
  20818. if (this.subMeshes) {
  20819. while (this.subMeshes.length) {
  20820. this.subMeshes[0].dispose();
  20821. }
  20822. }
  20823. else {
  20824. this.subMeshes = new Array();
  20825. }
  20826. return this;
  20827. };
  20828. /**
  20829. * Releases resources associated with this abstract mesh.
  20830. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20831. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20832. */
  20833. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20834. var _this = this;
  20835. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20836. var index;
  20837. // Smart Array Retainers.
  20838. this.getScene().freeActiveMeshes();
  20839. this.getScene().freeRenderingGroups();
  20840. // Action manager
  20841. if (this.actionManager !== undefined && this.actionManager !== null) {
  20842. this.actionManager.dispose();
  20843. this.actionManager = null;
  20844. }
  20845. // Skeleton
  20846. this._skeleton = null;
  20847. // Physics
  20848. if (this.physicsImpostor) {
  20849. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20850. }
  20851. // Intersections in progress
  20852. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20853. var other = this._intersectionsInProgress[index];
  20854. var pos = other._intersectionsInProgress.indexOf(this);
  20855. other._intersectionsInProgress.splice(pos, 1);
  20856. }
  20857. this._intersectionsInProgress = [];
  20858. // Lights
  20859. var lights = this.getScene().lights;
  20860. lights.forEach(function (light) {
  20861. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20862. if (meshIndex !== -1) {
  20863. light.includedOnlyMeshes.splice(meshIndex, 1);
  20864. }
  20865. meshIndex = light.excludedMeshes.indexOf(_this);
  20866. if (meshIndex !== -1) {
  20867. light.excludedMeshes.splice(meshIndex, 1);
  20868. }
  20869. // Shadow generators
  20870. var generator = light.getShadowGenerator();
  20871. if (generator) {
  20872. var shadowMap = generator.getShadowMap();
  20873. if (shadowMap && shadowMap.renderList) {
  20874. meshIndex = shadowMap.renderList.indexOf(_this);
  20875. if (meshIndex !== -1) {
  20876. shadowMap.renderList.splice(meshIndex, 1);
  20877. }
  20878. }
  20879. }
  20880. });
  20881. // Edges
  20882. if (this._edgesRenderer) {
  20883. this._edgesRenderer.dispose();
  20884. this._edgesRenderer = null;
  20885. }
  20886. // SubMeshes
  20887. if (this.getClassName() !== "InstancedMesh") {
  20888. this.releaseSubMeshes();
  20889. }
  20890. // Octree
  20891. var sceneOctree = this.getScene().selectionOctree;
  20892. if (sceneOctree !== undefined && sceneOctree !== null) {
  20893. var index = sceneOctree.dynamicContent.indexOf(this);
  20894. if (index !== -1) {
  20895. sceneOctree.dynamicContent.splice(index, 1);
  20896. }
  20897. }
  20898. // Query
  20899. var engine = this.getScene().getEngine();
  20900. if (this._occlusionQuery) {
  20901. this._isOcclusionQueryInProgress = false;
  20902. engine.deleteQuery(this._occlusionQuery);
  20903. this._occlusionQuery = null;
  20904. }
  20905. // Engine
  20906. engine.wipeCaches();
  20907. // Remove from scene
  20908. this.getScene().removeMesh(this);
  20909. if (disposeMaterialAndTextures) {
  20910. if (this.material) {
  20911. this.material.dispose(false, true);
  20912. }
  20913. }
  20914. if (!doNotRecurse) {
  20915. // Particles
  20916. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20917. if (this.getScene().particleSystems[index].emitter === this) {
  20918. this.getScene().particleSystems[index].dispose();
  20919. index--;
  20920. }
  20921. }
  20922. }
  20923. // facet data
  20924. if (this._facetDataEnabled) {
  20925. this.disableFacetData();
  20926. }
  20927. this.onAfterWorldMatrixUpdateObservable.clear();
  20928. this.onCollideObservable.clear();
  20929. this.onCollisionPositionChangeObservable.clear();
  20930. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20931. };
  20932. /**
  20933. * Adds the passed mesh as a child to the current mesh
  20934. * @param mesh defines the child mesh
  20935. * @returns the current mesh
  20936. */
  20937. AbstractMesh.prototype.addChild = function (mesh) {
  20938. mesh.setParent(this);
  20939. return this;
  20940. };
  20941. /**
  20942. * Removes the passed mesh from the current mesh children list
  20943. * @param mesh defines the child mesh
  20944. * @returns the current mesh
  20945. */
  20946. AbstractMesh.prototype.removeChild = function (mesh) {
  20947. mesh.setParent(null);
  20948. return this;
  20949. };
  20950. // Facet data
  20951. /** @hidden */
  20952. AbstractMesh.prototype._initFacetData = function () {
  20953. if (!this._facetNormals) {
  20954. this._facetNormals = new Array();
  20955. }
  20956. if (!this._facetPositions) {
  20957. this._facetPositions = new Array();
  20958. }
  20959. if (!this._facetPartitioning) {
  20960. this._facetPartitioning = new Array();
  20961. }
  20962. this._facetNb = (this.getIndices().length / 3) | 0;
  20963. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20964. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20965. for (var f = 0; f < this._facetNb; f++) {
  20966. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20967. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20968. }
  20969. this._facetDataEnabled = true;
  20970. return this;
  20971. };
  20972. /**
  20973. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20974. * This method can be called within the render loop.
  20975. * 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
  20976. * @returns the current mesh
  20977. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20978. */
  20979. AbstractMesh.prototype.updateFacetData = function () {
  20980. if (!this._facetDataEnabled) {
  20981. this._initFacetData();
  20982. }
  20983. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20984. var indices = this.getIndices();
  20985. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20986. var bInfo = this.getBoundingInfo();
  20987. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20988. // init arrays, matrix and sort function on first call
  20989. this._facetDepthSortEnabled = true;
  20990. if (indices instanceof Uint16Array) {
  20991. this._depthSortedIndices = new Uint16Array(indices);
  20992. }
  20993. else if (indices instanceof Uint32Array) {
  20994. this._depthSortedIndices = new Uint32Array(indices);
  20995. }
  20996. else {
  20997. var needs32bits = false;
  20998. for (var i = 0; i < indices.length; i++) {
  20999. if (indices[i] > 65535) {
  21000. needs32bits = true;
  21001. break;
  21002. }
  21003. }
  21004. if (needs32bits) {
  21005. this._depthSortedIndices = new Uint32Array(indices);
  21006. }
  21007. else {
  21008. this._depthSortedIndices = new Uint16Array(indices);
  21009. }
  21010. }
  21011. this._facetDepthSortFunction = function (f1, f2) {
  21012. return (f2.sqDistance - f1.sqDistance);
  21013. };
  21014. if (!this._facetDepthSortFrom) {
  21015. var camera = this.getScene().activeCamera;
  21016. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21017. }
  21018. this._depthSortedFacets = [];
  21019. for (var f = 0; f < this._facetNb; f++) {
  21020. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21021. this._depthSortedFacets.push(depthSortedFacet);
  21022. }
  21023. this._invertedMatrix = BABYLON.Matrix.Identity();
  21024. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21025. }
  21026. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21027. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21028. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21029. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21030. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21031. this._subDiv.max = this._partitioningSubdivisions;
  21032. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21033. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21034. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21035. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21036. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21037. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21038. // set the parameters for ComputeNormals()
  21039. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21040. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21041. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21042. this._facetParameters.bInfo = bInfo;
  21043. this._facetParameters.bbSize = this._bbSize;
  21044. this._facetParameters.subDiv = this._subDiv;
  21045. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21046. this._facetParameters.depthSort = this._facetDepthSort;
  21047. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21048. this.computeWorldMatrix(true);
  21049. this._worldMatrix.invertToRef(this._invertedMatrix);
  21050. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21051. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21052. }
  21053. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21054. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21055. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21056. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21057. var l = (this._depthSortedIndices.length / 3) | 0;
  21058. for (var f = 0; f < l; f++) {
  21059. var sind = this._depthSortedFacets[f].ind;
  21060. this._depthSortedIndices[f * 3] = indices[sind];
  21061. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21062. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21063. }
  21064. this.updateIndices(this._depthSortedIndices);
  21065. }
  21066. return this;
  21067. };
  21068. /**
  21069. * Returns the facetLocalNormals array.
  21070. * The normals are expressed in the mesh local spac
  21071. * @returns an array of Vector3
  21072. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21073. */
  21074. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21075. if (!this._facetNormals) {
  21076. this.updateFacetData();
  21077. }
  21078. return this._facetNormals;
  21079. };
  21080. /**
  21081. * Returns the facetLocalPositions array.
  21082. * The facet positions are expressed in the mesh local space
  21083. * @returns an array of Vector3
  21084. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21085. */
  21086. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21087. if (!this._facetPositions) {
  21088. this.updateFacetData();
  21089. }
  21090. return this._facetPositions;
  21091. };
  21092. /**
  21093. * Returns the facetLocalPartioning array
  21094. * @returns an array of array of numbers
  21095. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21096. */
  21097. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21098. if (!this._facetPartitioning) {
  21099. this.updateFacetData();
  21100. }
  21101. return this._facetPartitioning;
  21102. };
  21103. /**
  21104. * Returns the i-th facet position in the world system.
  21105. * This method allocates a new Vector3 per call
  21106. * @param i defines the facet index
  21107. * @returns a new Vector3
  21108. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21109. */
  21110. AbstractMesh.prototype.getFacetPosition = function (i) {
  21111. var pos = BABYLON.Vector3.Zero();
  21112. this.getFacetPositionToRef(i, pos);
  21113. return pos;
  21114. };
  21115. /**
  21116. * Sets the reference Vector3 with the i-th facet position in the world system
  21117. * @param i defines the facet index
  21118. * @param ref defines the target vector
  21119. * @returns the current mesh
  21120. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21121. */
  21122. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21123. var localPos = (this.getFacetLocalPositions())[i];
  21124. var world = this.getWorldMatrix();
  21125. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21126. return this;
  21127. };
  21128. /**
  21129. * Returns the i-th facet normal in the world system.
  21130. * This method allocates a new Vector3 per call
  21131. * @param i defines the facet index
  21132. * @returns a new Vector3
  21133. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21134. */
  21135. AbstractMesh.prototype.getFacetNormal = function (i) {
  21136. var norm = BABYLON.Vector3.Zero();
  21137. this.getFacetNormalToRef(i, norm);
  21138. return norm;
  21139. };
  21140. /**
  21141. * Sets the reference Vector3 with the i-th facet normal in the world system
  21142. * @param i defines the facet index
  21143. * @param ref defines the target vector
  21144. * @returns the current mesh
  21145. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21146. */
  21147. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21148. var localNorm = (this.getFacetLocalNormals())[i];
  21149. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21150. return this;
  21151. };
  21152. /**
  21153. * 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)
  21154. * @param x defines x coordinate
  21155. * @param y defines y coordinate
  21156. * @param z defines z coordinate
  21157. * @returns the array of facet indexes
  21158. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21159. */
  21160. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21161. var bInfo = this.getBoundingInfo();
  21162. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21163. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21164. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21165. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21166. return null;
  21167. }
  21168. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21169. };
  21170. /**
  21171. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21172. * @param projected sets as the (x,y,z) world projection on the facet
  21173. * @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
  21174. * @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
  21175. * @param x defines x coordinate
  21176. * @param y defines y coordinate
  21177. * @param z defines z coordinate
  21178. * @returns the face index if found (or null instead)
  21179. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21180. */
  21181. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21182. if (checkFace === void 0) { checkFace = false; }
  21183. if (facing === void 0) { facing = true; }
  21184. var world = this.getWorldMatrix();
  21185. var invMat = BABYLON.Tmp.Matrix[5];
  21186. world.invertToRef(invMat);
  21187. var invVect = BABYLON.Tmp.Vector3[8];
  21188. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21189. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21190. if (projected) {
  21191. // tranform the local computed projected vector to world coordinates
  21192. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21193. }
  21194. return closest;
  21195. };
  21196. /**
  21197. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21198. * @param projected sets as the (x,y,z) local projection on the facet
  21199. * @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
  21200. * @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
  21201. * @param x defines x coordinate
  21202. * @param y defines y coordinate
  21203. * @param z defines z coordinate
  21204. * @returns the face index if found (or null instead)
  21205. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21206. */
  21207. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21208. if (checkFace === void 0) { checkFace = false; }
  21209. if (facing === void 0) { facing = true; }
  21210. var closest = null;
  21211. var tmpx = 0.0;
  21212. var tmpy = 0.0;
  21213. var tmpz = 0.0;
  21214. var d = 0.0; // tmp dot facet normal * facet position
  21215. var t0 = 0.0;
  21216. var projx = 0.0;
  21217. var projy = 0.0;
  21218. var projz = 0.0;
  21219. // Get all the facets in the same partitioning block than (x, y, z)
  21220. var facetPositions = this.getFacetLocalPositions();
  21221. var facetNormals = this.getFacetLocalNormals();
  21222. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21223. if (!facetsInBlock) {
  21224. return null;
  21225. }
  21226. // Get the closest facet to (x, y, z)
  21227. var shortest = Number.MAX_VALUE; // init distance vars
  21228. var tmpDistance = shortest;
  21229. var fib; // current facet in the block
  21230. var norm; // current facet normal
  21231. var p0; // current facet barycenter position
  21232. // loop on all the facets in the current partitioning block
  21233. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21234. fib = facetsInBlock[idx];
  21235. norm = facetNormals[fib];
  21236. p0 = facetPositions[fib];
  21237. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21238. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21239. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21240. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21241. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21242. projx = x + norm.x * t0;
  21243. projy = y + norm.y * t0;
  21244. projz = z + norm.z * t0;
  21245. tmpx = projx - x;
  21246. tmpy = projy - y;
  21247. tmpz = projz - z;
  21248. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21249. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21250. shortest = tmpDistance;
  21251. closest = fib;
  21252. if (projected) {
  21253. projected.x = projx;
  21254. projected.y = projy;
  21255. projected.z = projz;
  21256. }
  21257. }
  21258. }
  21259. }
  21260. return closest;
  21261. };
  21262. /**
  21263. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21264. * @returns the parameters
  21265. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21266. */
  21267. AbstractMesh.prototype.getFacetDataParameters = function () {
  21268. return this._facetParameters;
  21269. };
  21270. /**
  21271. * Disables the feature FacetData and frees the related memory
  21272. * @returns the current mesh
  21273. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21274. */
  21275. AbstractMesh.prototype.disableFacetData = function () {
  21276. if (this._facetDataEnabled) {
  21277. this._facetDataEnabled = false;
  21278. this._facetPositions = new Array();
  21279. this._facetNormals = new Array();
  21280. this._facetPartitioning = new Array();
  21281. this._facetParameters = null;
  21282. this._depthSortedIndices = new Uint32Array(0);
  21283. }
  21284. return this;
  21285. };
  21286. /**
  21287. * Updates the AbstractMesh indices array
  21288. * @param indices defines the data source
  21289. * @returns the current mesh
  21290. */
  21291. AbstractMesh.prototype.updateIndices = function (indices) {
  21292. return this;
  21293. };
  21294. /**
  21295. * Creates new normals data for the mesh
  21296. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21297. * @returns the current mesh
  21298. */
  21299. AbstractMesh.prototype.createNormals = function (updatable) {
  21300. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21301. var indices = this.getIndices();
  21302. var normals;
  21303. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21304. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21305. }
  21306. else {
  21307. normals = [];
  21308. }
  21309. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21310. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21311. return this;
  21312. };
  21313. /**
  21314. * Align the mesh with a normal
  21315. * @param normal defines the normal to use
  21316. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21317. * @returns the current mesh
  21318. */
  21319. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21320. if (!upDirection) {
  21321. upDirection = BABYLON.Axis.Y;
  21322. }
  21323. var axisX = BABYLON.Tmp.Vector3[0];
  21324. var axisZ = BABYLON.Tmp.Vector3[1];
  21325. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21326. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21327. if (this.rotationQuaternion) {
  21328. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21329. }
  21330. else {
  21331. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21332. }
  21333. return this;
  21334. };
  21335. /** @hidden */
  21336. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21337. var engine = this.getEngine();
  21338. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21339. this._isOccluded = false;
  21340. return;
  21341. }
  21342. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21343. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21344. if (isOcclusionQueryAvailable) {
  21345. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21346. this._isOcclusionQueryInProgress = false;
  21347. this._occlusionInternalRetryCounter = 0;
  21348. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21349. }
  21350. else {
  21351. this._occlusionInternalRetryCounter++;
  21352. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21353. this._isOcclusionQueryInProgress = false;
  21354. this._occlusionInternalRetryCounter = 0;
  21355. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21356. // if strict continue the last state of the object.
  21357. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21358. }
  21359. else {
  21360. return;
  21361. }
  21362. }
  21363. }
  21364. var scene = this.getScene();
  21365. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21366. if (!this._occlusionQuery) {
  21367. this._occlusionQuery = engine.createQuery();
  21368. }
  21369. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21370. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21371. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21372. this._isOcclusionQueryInProgress = true;
  21373. };
  21374. /** No occlusion */
  21375. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21376. /** Occlusion set to optimisitic */
  21377. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21378. /** Occlusion set to strict */
  21379. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21380. /** Use an accurante occlusion algorithm */
  21381. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21382. /** Use a conservative occlusion algorithm */
  21383. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21384. return AbstractMesh;
  21385. }(BABYLON.TransformNode));
  21386. BABYLON.AbstractMesh = AbstractMesh;
  21387. })(BABYLON || (BABYLON = {}));
  21388. //# sourceMappingURL=babylon.abstractMesh.js.map
  21389. var BABYLON;
  21390. (function (BABYLON) {
  21391. /**
  21392. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21393. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21394. * 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.
  21395. */
  21396. var Light = /** @class */ (function (_super) {
  21397. __extends(Light, _super);
  21398. /**
  21399. * Creates a Light object in the scene.
  21400. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21401. * @param name The firendly name of the light
  21402. * @param scene The scene the light belongs too
  21403. */
  21404. function Light(name, scene) {
  21405. var _this = _super.call(this, name, scene) || this;
  21406. /**
  21407. * Diffuse gives the basic color to an object.
  21408. */
  21409. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21410. /**
  21411. * Specular produces a highlight color on an object.
  21412. * Note: This is note affecting PBR materials.
  21413. */
  21414. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21415. /**
  21416. * Strength of the light.
  21417. * Note: By default it is define in the framework own unit.
  21418. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21419. */
  21420. _this.intensity = 1.0;
  21421. /**
  21422. * Defines how far from the source the light is impacting in scene units.
  21423. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21424. */
  21425. _this.range = Number.MAX_VALUE;
  21426. /**
  21427. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21428. * of light.
  21429. */
  21430. _this._photometricScale = 1.0;
  21431. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21432. _this._radius = 0.00001;
  21433. /**
  21434. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21435. * exceeding the number allowed of the materials.
  21436. */
  21437. _this.renderPriority = 0;
  21438. _this._shadowEnabled = true;
  21439. _this._excludeWithLayerMask = 0;
  21440. _this._includeOnlyWithLayerMask = 0;
  21441. _this._lightmapMode = 0;
  21442. /**
  21443. * @hidden Internal use only.
  21444. */
  21445. _this._excludedMeshesIds = new Array();
  21446. /**
  21447. * @hidden Internal use only.
  21448. */
  21449. _this._includedOnlyMeshesIds = new Array();
  21450. _this.getScene().addLight(_this);
  21451. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21452. _this._buildUniformLayout();
  21453. _this.includedOnlyMeshes = new Array();
  21454. _this.excludedMeshes = new Array();
  21455. _this._resyncMeshes();
  21456. return _this;
  21457. }
  21458. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21459. /**
  21460. * If every light affecting the material is in this lightmapMode,
  21461. * material.lightmapTexture adds or multiplies
  21462. * (depends on material.useLightmapAsShadowmap)
  21463. * after every other light calculations.
  21464. */
  21465. get: function () {
  21466. return Light._LIGHTMAP_DEFAULT;
  21467. },
  21468. enumerable: true,
  21469. configurable: true
  21470. });
  21471. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21472. /**
  21473. * material.lightmapTexture as only diffuse lighting from this light
  21474. * adds only specular lighting from this light
  21475. * adds dynamic shadows
  21476. */
  21477. get: function () {
  21478. return Light._LIGHTMAP_SPECULAR;
  21479. },
  21480. enumerable: true,
  21481. configurable: true
  21482. });
  21483. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21484. /**
  21485. * material.lightmapTexture as only lighting
  21486. * no light calculation from this light
  21487. * only adds dynamic shadows from this light
  21488. */
  21489. get: function () {
  21490. return Light._LIGHTMAP_SHADOWSONLY;
  21491. },
  21492. enumerable: true,
  21493. configurable: true
  21494. });
  21495. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21496. /**
  21497. * Each light type uses the default quantity according to its type:
  21498. * point/spot lights use luminous intensity
  21499. * directional lights use illuminance
  21500. */
  21501. get: function () {
  21502. return Light._INTENSITYMODE_AUTOMATIC;
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21508. /**
  21509. * lumen (lm)
  21510. */
  21511. get: function () {
  21512. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21518. /**
  21519. * candela (lm/sr)
  21520. */
  21521. get: function () {
  21522. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21528. /**
  21529. * lux (lm/m^2)
  21530. */
  21531. get: function () {
  21532. return Light._INTENSITYMODE_ILLUMINANCE;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21538. /**
  21539. * nit (cd/m^2)
  21540. */
  21541. get: function () {
  21542. return Light._INTENSITYMODE_LUMINANCE;
  21543. },
  21544. enumerable: true,
  21545. configurable: true
  21546. });
  21547. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21548. /**
  21549. * Light type const id of the point light.
  21550. */
  21551. get: function () {
  21552. return Light._LIGHTTYPEID_POINTLIGHT;
  21553. },
  21554. enumerable: true,
  21555. configurable: true
  21556. });
  21557. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21558. /**
  21559. * Light type const id of the directional light.
  21560. */
  21561. get: function () {
  21562. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21568. /**
  21569. * Light type const id of the spot light.
  21570. */
  21571. get: function () {
  21572. return Light._LIGHTTYPEID_SPOTLIGHT;
  21573. },
  21574. enumerable: true,
  21575. configurable: true
  21576. });
  21577. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21578. /**
  21579. * Light type const id of the hemispheric light.
  21580. */
  21581. get: function () {
  21582. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21583. },
  21584. enumerable: true,
  21585. configurable: true
  21586. });
  21587. Object.defineProperty(Light.prototype, "intensityMode", {
  21588. /**
  21589. * Gets the photometric scale used to interpret the intensity.
  21590. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21591. */
  21592. get: function () {
  21593. return this._intensityMode;
  21594. },
  21595. /**
  21596. * Sets the photometric scale used to interpret the intensity.
  21597. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21598. */
  21599. set: function (value) {
  21600. this._intensityMode = value;
  21601. this._computePhotometricScale();
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. ;
  21607. ;
  21608. Object.defineProperty(Light.prototype, "radius", {
  21609. /**
  21610. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21611. */
  21612. get: function () {
  21613. return this._radius;
  21614. },
  21615. /**
  21616. * sets the light radius used by PBR Materials to simulate soft area lights.
  21617. */
  21618. set: function (value) {
  21619. this._radius = value;
  21620. this._computePhotometricScale();
  21621. },
  21622. enumerable: true,
  21623. configurable: true
  21624. });
  21625. ;
  21626. ;
  21627. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21628. /**
  21629. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21630. * the current shadow generator.
  21631. */
  21632. get: function () {
  21633. return this._shadowEnabled;
  21634. },
  21635. /**
  21636. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21637. * the current shadow generator.
  21638. */
  21639. set: function (value) {
  21640. if (this._shadowEnabled === value) {
  21641. return;
  21642. }
  21643. this._shadowEnabled = value;
  21644. this._markMeshesAsLightDirty();
  21645. },
  21646. enumerable: true,
  21647. configurable: true
  21648. });
  21649. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21650. /**
  21651. * Gets the only meshes impacted by this light.
  21652. */
  21653. get: function () {
  21654. return this._includedOnlyMeshes;
  21655. },
  21656. /**
  21657. * Sets the only meshes impacted by this light.
  21658. */
  21659. set: function (value) {
  21660. this._includedOnlyMeshes = value;
  21661. this._hookArrayForIncludedOnly(value);
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21667. /**
  21668. * Gets the meshes not impacted by this light.
  21669. */
  21670. get: function () {
  21671. return this._excludedMeshes;
  21672. },
  21673. /**
  21674. * Sets the meshes not impacted by this light.
  21675. */
  21676. set: function (value) {
  21677. this._excludedMeshes = value;
  21678. this._hookArrayForExcluded(value);
  21679. },
  21680. enumerable: true,
  21681. configurable: true
  21682. });
  21683. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21684. /**
  21685. * Gets the layer id use to find what meshes are not impacted by the light.
  21686. * Inactive if 0
  21687. */
  21688. get: function () {
  21689. return this._excludeWithLayerMask;
  21690. },
  21691. /**
  21692. * Sets the layer id use to find what meshes are not impacted by the light.
  21693. * Inactive if 0
  21694. */
  21695. set: function (value) {
  21696. this._excludeWithLayerMask = value;
  21697. this._resyncMeshes();
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21703. /**
  21704. * Gets the layer id use to find what meshes are impacted by the light.
  21705. * Inactive if 0
  21706. */
  21707. get: function () {
  21708. return this._includeOnlyWithLayerMask;
  21709. },
  21710. /**
  21711. * Sets the layer id use to find what meshes are impacted by the light.
  21712. * Inactive if 0
  21713. */
  21714. set: function (value) {
  21715. this._includeOnlyWithLayerMask = value;
  21716. this._resyncMeshes();
  21717. },
  21718. enumerable: true,
  21719. configurable: true
  21720. });
  21721. Object.defineProperty(Light.prototype, "lightmapMode", {
  21722. /**
  21723. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21724. */
  21725. get: function () {
  21726. return this._lightmapMode;
  21727. },
  21728. /**
  21729. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21730. */
  21731. set: function (value) {
  21732. if (this._lightmapMode === value) {
  21733. return;
  21734. }
  21735. this._lightmapMode = value;
  21736. this._markMeshesAsLightDirty();
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. /**
  21742. * Returns the string "Light".
  21743. * @returns the class name
  21744. */
  21745. Light.prototype.getClassName = function () {
  21746. return "Light";
  21747. };
  21748. /**
  21749. * Converts the light information to a readable string for debug purpose.
  21750. * @param fullDetails Supports for multiple levels of logging within scene loading
  21751. * @returns the human readable light info
  21752. */
  21753. Light.prototype.toString = function (fullDetails) {
  21754. var ret = "Name: " + this.name;
  21755. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21756. if (this.animations) {
  21757. for (var i = 0; i < this.animations.length; i++) {
  21758. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21759. }
  21760. }
  21761. if (fullDetails) {
  21762. }
  21763. return ret;
  21764. };
  21765. /**
  21766. * Set the enabled state of this node.
  21767. * @param value - the new enabled state
  21768. */
  21769. Light.prototype.setEnabled = function (value) {
  21770. _super.prototype.setEnabled.call(this, value);
  21771. this._resyncMeshes();
  21772. };
  21773. /**
  21774. * Returns the Light associated shadow generator if any.
  21775. * @return the associated shadow generator.
  21776. */
  21777. Light.prototype.getShadowGenerator = function () {
  21778. return this._shadowGenerator;
  21779. };
  21780. /**
  21781. * Returns a Vector3, the absolute light position in the World.
  21782. * @returns the world space position of the light
  21783. */
  21784. Light.prototype.getAbsolutePosition = function () {
  21785. return BABYLON.Vector3.Zero();
  21786. };
  21787. /**
  21788. * Specifies if the light will affect the passed mesh.
  21789. * @param mesh The mesh to test against the light
  21790. * @return true the mesh is affected otherwise, false.
  21791. */
  21792. Light.prototype.canAffectMesh = function (mesh) {
  21793. if (!mesh) {
  21794. return true;
  21795. }
  21796. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21797. return false;
  21798. }
  21799. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21800. return false;
  21801. }
  21802. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21803. return false;
  21804. }
  21805. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21806. return false;
  21807. }
  21808. return true;
  21809. };
  21810. /**
  21811. * Computes and Returns the light World matrix.
  21812. * @returns the world matrix
  21813. */
  21814. Light.prototype.getWorldMatrix = function () {
  21815. this._currentRenderId = this.getScene().getRenderId();
  21816. this._childRenderId = this._currentRenderId;
  21817. var worldMatrix = this._getWorldMatrix();
  21818. if (this.parent && this.parent.getWorldMatrix) {
  21819. if (!this._parentedWorldMatrix) {
  21820. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21821. }
  21822. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21823. this._markSyncedWithParent();
  21824. return this._parentedWorldMatrix;
  21825. }
  21826. return worldMatrix;
  21827. };
  21828. /**
  21829. * Sort function to order lights for rendering.
  21830. * @param a First Light object to compare to second.
  21831. * @param b Second Light object to compare first.
  21832. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21833. */
  21834. Light.CompareLightsPriority = function (a, b) {
  21835. //shadow-casting lights have priority over non-shadow-casting lights
  21836. //the renderPrioirty is a secondary sort criterion
  21837. if (a.shadowEnabled !== b.shadowEnabled) {
  21838. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21839. }
  21840. return b.renderPriority - a.renderPriority;
  21841. };
  21842. /**
  21843. * Releases resources associated with this node.
  21844. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21845. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21846. */
  21847. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21848. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21849. if (this._shadowGenerator) {
  21850. this._shadowGenerator.dispose();
  21851. this._shadowGenerator = null;
  21852. }
  21853. // Animations
  21854. this.getScene().stopAnimation(this);
  21855. // Remove from meshes
  21856. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21857. var mesh = _a[_i];
  21858. mesh._removeLightSource(this);
  21859. }
  21860. this._uniformBuffer.dispose();
  21861. // Remove from scene
  21862. this.getScene().removeLight(this);
  21863. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21864. };
  21865. /**
  21866. * Returns the light type ID (integer).
  21867. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21868. */
  21869. Light.prototype.getTypeID = function () {
  21870. return 0;
  21871. };
  21872. /**
  21873. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21874. * @returns the scaled intensity in intensity mode unit
  21875. */
  21876. Light.prototype.getScaledIntensity = function () {
  21877. return this._photometricScale * this.intensity;
  21878. };
  21879. /**
  21880. * Returns a new Light object, named "name", from the current one.
  21881. * @param name The name of the cloned light
  21882. * @returns the new created light
  21883. */
  21884. Light.prototype.clone = function (name) {
  21885. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21886. if (!constructor) {
  21887. return null;
  21888. }
  21889. return BABYLON.SerializationHelper.Clone(constructor, this);
  21890. };
  21891. /**
  21892. * Serializes the current light into a Serialization object.
  21893. * @returns the serialized object.
  21894. */
  21895. Light.prototype.serialize = function () {
  21896. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21897. // Type
  21898. serializationObject.type = this.getTypeID();
  21899. // Parent
  21900. if (this.parent) {
  21901. serializationObject.parentId = this.parent.id;
  21902. }
  21903. // Inclusion / exclusions
  21904. if (this.excludedMeshes.length > 0) {
  21905. serializationObject.excludedMeshesIds = [];
  21906. this.excludedMeshes.forEach(function (mesh) {
  21907. serializationObject.excludedMeshesIds.push(mesh.id);
  21908. });
  21909. }
  21910. if (this.includedOnlyMeshes.length > 0) {
  21911. serializationObject.includedOnlyMeshesIds = [];
  21912. this.includedOnlyMeshes.forEach(function (mesh) {
  21913. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21914. });
  21915. }
  21916. // Animations
  21917. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21918. serializationObject.ranges = this.serializeAnimationRanges();
  21919. return serializationObject;
  21920. };
  21921. /**
  21922. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21923. * This new light is named "name" and added to the passed scene.
  21924. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21925. * @param name The friendly name of the light
  21926. * @param scene The scene the new light will belong to
  21927. * @returns the constructor function
  21928. */
  21929. Light.GetConstructorFromName = function (type, name, scene) {
  21930. switch (type) {
  21931. case 0:
  21932. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21933. case 1:
  21934. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21935. case 2:
  21936. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21937. case 3:
  21938. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21939. }
  21940. return null;
  21941. };
  21942. /**
  21943. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21944. * @param parsedLight The JSON representation of the light
  21945. * @param scene The scene to create the parsed light in
  21946. * @returns the created light after parsing
  21947. */
  21948. Light.Parse = function (parsedLight, scene) {
  21949. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21950. if (!constructor) {
  21951. return null;
  21952. }
  21953. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21954. // Inclusion / exclusions
  21955. if (parsedLight.excludedMeshesIds) {
  21956. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21957. }
  21958. if (parsedLight.includedOnlyMeshesIds) {
  21959. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21960. }
  21961. // Parent
  21962. if (parsedLight.parentId) {
  21963. light._waitingParentId = parsedLight.parentId;
  21964. }
  21965. // Animations
  21966. if (parsedLight.animations) {
  21967. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21968. var parsedAnimation = parsedLight.animations[animationIndex];
  21969. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21970. }
  21971. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21972. }
  21973. if (parsedLight.autoAnimate) {
  21974. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21975. }
  21976. return light;
  21977. };
  21978. Light.prototype._hookArrayForExcluded = function (array) {
  21979. var _this = this;
  21980. var oldPush = array.push;
  21981. array.push = function () {
  21982. var items = [];
  21983. for (var _i = 0; _i < arguments.length; _i++) {
  21984. items[_i] = arguments[_i];
  21985. }
  21986. var result = oldPush.apply(array, items);
  21987. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21988. var item = items_1[_a];
  21989. item._resyncLighSource(_this);
  21990. }
  21991. return result;
  21992. };
  21993. var oldSplice = array.splice;
  21994. array.splice = function (index, deleteCount) {
  21995. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21996. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21997. var item = deleted_1[_i];
  21998. item._resyncLighSource(_this);
  21999. }
  22000. return deleted;
  22001. };
  22002. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22003. var item = array_1[_i];
  22004. item._resyncLighSource(this);
  22005. }
  22006. };
  22007. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22008. var _this = this;
  22009. var oldPush = array.push;
  22010. array.push = function () {
  22011. var items = [];
  22012. for (var _i = 0; _i < arguments.length; _i++) {
  22013. items[_i] = arguments[_i];
  22014. }
  22015. var result = oldPush.apply(array, items);
  22016. _this._resyncMeshes();
  22017. return result;
  22018. };
  22019. var oldSplice = array.splice;
  22020. array.splice = function (index, deleteCount) {
  22021. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22022. _this._resyncMeshes();
  22023. return deleted;
  22024. };
  22025. this._resyncMeshes();
  22026. };
  22027. Light.prototype._resyncMeshes = function () {
  22028. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22029. var mesh = _a[_i];
  22030. mesh._resyncLighSource(this);
  22031. }
  22032. };
  22033. /**
  22034. * Forces the meshes to update their light related information in their rendering used effects
  22035. * @hidden Internal Use Only
  22036. */
  22037. Light.prototype._markMeshesAsLightDirty = function () {
  22038. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22039. var mesh = _a[_i];
  22040. if (mesh._lightSources.indexOf(this) !== -1) {
  22041. mesh._markSubMeshesAsLightDirty();
  22042. }
  22043. }
  22044. };
  22045. /**
  22046. * Recomputes the cached photometric scale if needed.
  22047. */
  22048. Light.prototype._computePhotometricScale = function () {
  22049. this._photometricScale = this._getPhotometricScale();
  22050. this.getScene().resetCachedMaterial();
  22051. };
  22052. /**
  22053. * Returns the Photometric Scale according to the light type and intensity mode.
  22054. */
  22055. Light.prototype._getPhotometricScale = function () {
  22056. var photometricScale = 0.0;
  22057. var lightTypeID = this.getTypeID();
  22058. //get photometric mode
  22059. var photometricMode = this.intensityMode;
  22060. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22061. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22062. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22063. }
  22064. else {
  22065. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22066. }
  22067. }
  22068. //compute photometric scale
  22069. switch (lightTypeID) {
  22070. case Light.LIGHTTYPEID_POINTLIGHT:
  22071. case Light.LIGHTTYPEID_SPOTLIGHT:
  22072. switch (photometricMode) {
  22073. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22074. photometricScale = 1.0 / (4.0 * Math.PI);
  22075. break;
  22076. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22077. photometricScale = 1.0;
  22078. break;
  22079. case Light.INTENSITYMODE_LUMINANCE:
  22080. photometricScale = this.radius * this.radius;
  22081. break;
  22082. }
  22083. break;
  22084. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22085. switch (photometricMode) {
  22086. case Light.INTENSITYMODE_ILLUMINANCE:
  22087. photometricScale = 1.0;
  22088. break;
  22089. case Light.INTENSITYMODE_LUMINANCE:
  22090. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22091. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22092. var apexAngleRadians = this.radius;
  22093. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22094. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22095. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22096. photometricScale = solidAngle;
  22097. break;
  22098. }
  22099. break;
  22100. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22101. // No fall off in hemisperic light.
  22102. photometricScale = 1.0;
  22103. break;
  22104. }
  22105. return photometricScale;
  22106. };
  22107. /**
  22108. * Reorder the light in the scene according to their defined priority.
  22109. * @hidden Internal Use Only
  22110. */
  22111. Light.prototype._reorderLightsInScene = function () {
  22112. var scene = this.getScene();
  22113. if (this._renderPriority != 0) {
  22114. scene.requireLightSorting = true;
  22115. }
  22116. this.getScene().sortLightsByPriority();
  22117. };
  22118. //lightmapMode Consts
  22119. Light._LIGHTMAP_DEFAULT = 0;
  22120. Light._LIGHTMAP_SPECULAR = 1;
  22121. Light._LIGHTMAP_SHADOWSONLY = 2;
  22122. // Intensity Mode Consts
  22123. Light._INTENSITYMODE_AUTOMATIC = 0;
  22124. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22125. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22126. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22127. Light._INTENSITYMODE_LUMINANCE = 4;
  22128. // Light types ids const.
  22129. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22130. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22131. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22132. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22133. __decorate([
  22134. BABYLON.serializeAsColor3()
  22135. ], Light.prototype, "diffuse", void 0);
  22136. __decorate([
  22137. BABYLON.serializeAsColor3()
  22138. ], Light.prototype, "specular", void 0);
  22139. __decorate([
  22140. BABYLON.serialize()
  22141. ], Light.prototype, "intensity", void 0);
  22142. __decorate([
  22143. BABYLON.serialize()
  22144. ], Light.prototype, "range", void 0);
  22145. __decorate([
  22146. BABYLON.serialize()
  22147. ], Light.prototype, "intensityMode", null);
  22148. __decorate([
  22149. BABYLON.serialize()
  22150. ], Light.prototype, "radius", null);
  22151. __decorate([
  22152. BABYLON.serialize()
  22153. ], Light.prototype, "_renderPriority", void 0);
  22154. __decorate([
  22155. BABYLON.expandToProperty("_reorderLightsInScene")
  22156. ], Light.prototype, "renderPriority", void 0);
  22157. __decorate([
  22158. BABYLON.serialize("shadowEnabled")
  22159. ], Light.prototype, "_shadowEnabled", void 0);
  22160. __decorate([
  22161. BABYLON.serialize("excludeWithLayerMask")
  22162. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22163. __decorate([
  22164. BABYLON.serialize("includeOnlyWithLayerMask")
  22165. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22166. __decorate([
  22167. BABYLON.serialize("lightmapMode")
  22168. ], Light.prototype, "_lightmapMode", void 0);
  22169. return Light;
  22170. }(BABYLON.Node));
  22171. BABYLON.Light = Light;
  22172. })(BABYLON || (BABYLON = {}));
  22173. //# sourceMappingURL=babylon.light.js.map
  22174. var BABYLON;
  22175. (function (BABYLON) {
  22176. var Camera = /** @class */ (function (_super) {
  22177. __extends(Camera, _super);
  22178. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22179. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22180. var _this = _super.call(this, name, scene) || this;
  22181. /**
  22182. * The vector the camera should consider as up.
  22183. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22184. */
  22185. _this.upVector = BABYLON.Vector3.Up();
  22186. _this.orthoLeft = null;
  22187. _this.orthoRight = null;
  22188. _this.orthoBottom = null;
  22189. _this.orthoTop = null;
  22190. /**
  22191. * FOV is set in Radians. (default is 0.8)
  22192. */
  22193. _this.fov = 0.8;
  22194. _this.minZ = 1;
  22195. _this.maxZ = 10000.0;
  22196. _this.inertia = 0.9;
  22197. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22198. _this.isIntermediate = false;
  22199. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22200. /**
  22201. * Restricts the camera to viewing objects with the same layerMask.
  22202. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22203. */
  22204. _this.layerMask = 0x0FFFFFFF;
  22205. /**
  22206. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22207. */
  22208. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22209. // Camera rig members
  22210. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22211. _this._rigCameras = new Array();
  22212. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22213. _this._skipRendering = false;
  22214. _this.customRenderTargets = new Array();
  22215. // Observables
  22216. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22217. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22218. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22219. _this.onRestoreStateObservable = new BABYLON.Observable();
  22220. // Cache
  22221. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22222. _this._projectionMatrix = new BABYLON.Matrix();
  22223. _this._doNotComputeProjectionMatrix = false;
  22224. _this._worldMatrix = BABYLON.Matrix.Identity();
  22225. _this._postProcesses = new Array();
  22226. _this._transformMatrix = BABYLON.Matrix.Zero();
  22227. _this._activeMeshes = new BABYLON.SmartArray(256);
  22228. _this._globalPosition = BABYLON.Vector3.Zero();
  22229. _this._refreshFrustumPlanes = true;
  22230. _this.getScene().addCamera(_this);
  22231. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22232. _this.getScene().activeCamera = _this;
  22233. }
  22234. _this.position = position;
  22235. return _this;
  22236. }
  22237. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22238. get: function () {
  22239. return Camera._PERSPECTIVE_CAMERA;
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22245. get: function () {
  22246. return Camera._ORTHOGRAPHIC_CAMERA;
  22247. },
  22248. enumerable: true,
  22249. configurable: true
  22250. });
  22251. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22252. /**
  22253. * This is the default FOV mode for perspective cameras.
  22254. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22255. *
  22256. */
  22257. get: function () {
  22258. return Camera._FOVMODE_VERTICAL_FIXED;
  22259. },
  22260. enumerable: true,
  22261. configurable: true
  22262. });
  22263. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22264. /**
  22265. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22266. *
  22267. */
  22268. get: function () {
  22269. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22270. },
  22271. enumerable: true,
  22272. configurable: true
  22273. });
  22274. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22275. get: function () {
  22276. return Camera._RIG_MODE_NONE;
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22282. get: function () {
  22283. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22284. },
  22285. enumerable: true,
  22286. configurable: true
  22287. });
  22288. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22289. get: function () {
  22290. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22291. },
  22292. enumerable: true,
  22293. configurable: true
  22294. });
  22295. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22296. get: function () {
  22297. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22298. },
  22299. enumerable: true,
  22300. configurable: true
  22301. });
  22302. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22303. get: function () {
  22304. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22305. },
  22306. enumerable: true,
  22307. configurable: true
  22308. });
  22309. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22310. get: function () {
  22311. return Camera._RIG_MODE_VR;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22317. get: function () {
  22318. return Camera._RIG_MODE_WEBVR;
  22319. },
  22320. enumerable: true,
  22321. configurable: true
  22322. });
  22323. /**
  22324. * Store current camera state (fov, position, etc..)
  22325. */
  22326. Camera.prototype.storeState = function () {
  22327. this._stateStored = true;
  22328. this._storedFov = this.fov;
  22329. return this;
  22330. };
  22331. /**
  22332. * Restores the camera state values if it has been stored. You must call storeState() first
  22333. */
  22334. Camera.prototype._restoreStateValues = function () {
  22335. if (!this._stateStored) {
  22336. return false;
  22337. }
  22338. this.fov = this._storedFov;
  22339. return true;
  22340. };
  22341. /**
  22342. * Restored camera state. You must call storeState() first
  22343. */
  22344. Camera.prototype.restoreState = function () {
  22345. if (this._restoreStateValues()) {
  22346. this.onRestoreStateObservable.notifyObservers(this);
  22347. return true;
  22348. }
  22349. return false;
  22350. };
  22351. Camera.prototype.getClassName = function () {
  22352. return "Camera";
  22353. };
  22354. /**
  22355. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22356. */
  22357. Camera.prototype.toString = function (fullDetails) {
  22358. var ret = "Name: " + this.name;
  22359. ret += ", type: " + this.getClassName();
  22360. if (this.animations) {
  22361. for (var i = 0; i < this.animations.length; i++) {
  22362. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22363. }
  22364. }
  22365. if (fullDetails) {
  22366. }
  22367. return ret;
  22368. };
  22369. Object.defineProperty(Camera.prototype, "globalPosition", {
  22370. get: function () {
  22371. return this._globalPosition;
  22372. },
  22373. enumerable: true,
  22374. configurable: true
  22375. });
  22376. Camera.prototype.getActiveMeshes = function () {
  22377. return this._activeMeshes;
  22378. };
  22379. Camera.prototype.isActiveMesh = function (mesh) {
  22380. return (this._activeMeshes.indexOf(mesh) !== -1);
  22381. };
  22382. /**
  22383. * Is this camera ready to be used/rendered
  22384. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22385. * @return true if the camera is ready
  22386. */
  22387. Camera.prototype.isReady = function (completeCheck) {
  22388. if (completeCheck === void 0) { completeCheck = false; }
  22389. if (completeCheck) {
  22390. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22391. var pp = _a[_i];
  22392. if (pp && !pp.isReady()) {
  22393. return false;
  22394. }
  22395. }
  22396. }
  22397. return _super.prototype.isReady.call(this, completeCheck);
  22398. };
  22399. //Cache
  22400. Camera.prototype._initCache = function () {
  22401. _super.prototype._initCache.call(this);
  22402. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22403. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22404. this._cache.mode = undefined;
  22405. this._cache.minZ = undefined;
  22406. this._cache.maxZ = undefined;
  22407. this._cache.fov = undefined;
  22408. this._cache.fovMode = undefined;
  22409. this._cache.aspectRatio = undefined;
  22410. this._cache.orthoLeft = undefined;
  22411. this._cache.orthoRight = undefined;
  22412. this._cache.orthoBottom = undefined;
  22413. this._cache.orthoTop = undefined;
  22414. this._cache.renderWidth = undefined;
  22415. this._cache.renderHeight = undefined;
  22416. };
  22417. Camera.prototype._updateCache = function (ignoreParentClass) {
  22418. if (!ignoreParentClass) {
  22419. _super.prototype._updateCache.call(this);
  22420. }
  22421. this._cache.position.copyFrom(this.position);
  22422. this._cache.upVector.copyFrom(this.upVector);
  22423. };
  22424. // Synchronized
  22425. Camera.prototype._isSynchronized = function () {
  22426. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22427. };
  22428. Camera.prototype._isSynchronizedViewMatrix = function () {
  22429. if (!_super.prototype._isSynchronized.call(this))
  22430. return false;
  22431. return this._cache.position.equals(this.position)
  22432. && this._cache.upVector.equals(this.upVector)
  22433. && this.isSynchronizedWithParent();
  22434. };
  22435. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22436. var check = this._cache.mode === this.mode
  22437. && this._cache.minZ === this.minZ
  22438. && this._cache.maxZ === this.maxZ;
  22439. if (!check) {
  22440. return false;
  22441. }
  22442. var engine = this.getEngine();
  22443. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22444. check = this._cache.fov === this.fov
  22445. && this._cache.fovMode === this.fovMode
  22446. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22447. }
  22448. else {
  22449. check = this._cache.orthoLeft === this.orthoLeft
  22450. && this._cache.orthoRight === this.orthoRight
  22451. && this._cache.orthoBottom === this.orthoBottom
  22452. && this._cache.orthoTop === this.orthoTop
  22453. && this._cache.renderWidth === engine.getRenderWidth()
  22454. && this._cache.renderHeight === engine.getRenderHeight();
  22455. }
  22456. return check;
  22457. };
  22458. // Controls
  22459. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22460. };
  22461. Camera.prototype.detachControl = function (element) {
  22462. };
  22463. Camera.prototype.update = function () {
  22464. this._checkInputs();
  22465. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22466. this._updateRigCameras();
  22467. }
  22468. };
  22469. Camera.prototype._checkInputs = function () {
  22470. this.onAfterCheckInputsObservable.notifyObservers(this);
  22471. };
  22472. Object.defineProperty(Camera.prototype, "rigCameras", {
  22473. get: function () {
  22474. return this._rigCameras;
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22480. get: function () {
  22481. return this._rigPostProcess;
  22482. },
  22483. enumerable: true,
  22484. configurable: true
  22485. });
  22486. /**
  22487. * Internal, gets the first post proces.
  22488. * @returns the first post process to be run on this camera.
  22489. */
  22490. Camera.prototype._getFirstPostProcess = function () {
  22491. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22492. if (this._postProcesses[ppIndex] !== null) {
  22493. return this._postProcesses[ppIndex];
  22494. }
  22495. }
  22496. return null;
  22497. };
  22498. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22499. // invalidate framebuffer
  22500. var firstPostProcess = this._getFirstPostProcess();
  22501. if (firstPostProcess) {
  22502. firstPostProcess.markTextureDirty();
  22503. }
  22504. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22505. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22506. var cam = this._rigCameras[i];
  22507. var rigPostProcess = cam._rigPostProcess;
  22508. // for VR rig, there does not have to be a post process
  22509. if (rigPostProcess) {
  22510. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22511. if (isPass) {
  22512. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22513. cam.isIntermediate = this._postProcesses.length === 0;
  22514. }
  22515. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22516. rigPostProcess.markTextureDirty();
  22517. }
  22518. else {
  22519. cam._postProcesses = this._postProcesses.slice(0);
  22520. }
  22521. }
  22522. };
  22523. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22524. if (insertAt === void 0) { insertAt = null; }
  22525. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22526. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22527. return 0;
  22528. }
  22529. if (insertAt == null || insertAt < 0) {
  22530. this._postProcesses.push(postProcess);
  22531. }
  22532. else if (this._postProcesses[insertAt] === null) {
  22533. this._postProcesses[insertAt] = postProcess;
  22534. }
  22535. else {
  22536. this._postProcesses.splice(insertAt, 0, postProcess);
  22537. }
  22538. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22539. return this._postProcesses.indexOf(postProcess);
  22540. };
  22541. Camera.prototype.detachPostProcess = function (postProcess) {
  22542. var idx = this._postProcesses.indexOf(postProcess);
  22543. if (idx !== -1) {
  22544. this._postProcesses[idx] = null;
  22545. }
  22546. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22547. };
  22548. Camera.prototype.getWorldMatrix = function () {
  22549. if (this._isSynchronizedViewMatrix()) {
  22550. return this._worldMatrix;
  22551. }
  22552. // Getting the the view matrix will also compute the world matrix.
  22553. this.getViewMatrix();
  22554. return this._worldMatrix;
  22555. };
  22556. Camera.prototype._getViewMatrix = function () {
  22557. return BABYLON.Matrix.Identity();
  22558. };
  22559. Camera.prototype.getViewMatrix = function (force) {
  22560. if (!force && this._isSynchronizedViewMatrix()) {
  22561. return this._computedViewMatrix;
  22562. }
  22563. this.updateCache();
  22564. this._computedViewMatrix = this._getViewMatrix();
  22565. this._currentRenderId = this.getScene().getRenderId();
  22566. this._childRenderId = this._currentRenderId;
  22567. this._refreshFrustumPlanes = true;
  22568. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22569. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22570. }
  22571. this.onViewMatrixChangedObservable.notifyObservers(this);
  22572. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22573. return this._computedViewMatrix;
  22574. };
  22575. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22576. this._doNotComputeProjectionMatrix = true;
  22577. if (projection !== undefined) {
  22578. this._projectionMatrix = projection;
  22579. }
  22580. };
  22581. ;
  22582. Camera.prototype.unfreezeProjectionMatrix = function () {
  22583. this._doNotComputeProjectionMatrix = false;
  22584. };
  22585. ;
  22586. Camera.prototype.getProjectionMatrix = function (force) {
  22587. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22588. return this._projectionMatrix;
  22589. }
  22590. // Cache
  22591. this._cache.mode = this.mode;
  22592. this._cache.minZ = this.minZ;
  22593. this._cache.maxZ = this.maxZ;
  22594. // Matrix
  22595. this._refreshFrustumPlanes = true;
  22596. var engine = this.getEngine();
  22597. var scene = this.getScene();
  22598. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22599. this._cache.fov = this.fov;
  22600. this._cache.fovMode = this.fovMode;
  22601. this._cache.aspectRatio = engine.getAspectRatio(this);
  22602. if (this.minZ <= 0) {
  22603. this.minZ = 0.1;
  22604. }
  22605. if (scene.useRightHandedSystem) {
  22606. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22607. }
  22608. else {
  22609. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22610. }
  22611. }
  22612. else {
  22613. var halfWidth = engine.getRenderWidth() / 2.0;
  22614. var halfHeight = engine.getRenderHeight() / 2.0;
  22615. if (scene.useRightHandedSystem) {
  22616. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22617. }
  22618. else {
  22619. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22620. }
  22621. this._cache.orthoLeft = this.orthoLeft;
  22622. this._cache.orthoRight = this.orthoRight;
  22623. this._cache.orthoBottom = this.orthoBottom;
  22624. this._cache.orthoTop = this.orthoTop;
  22625. this._cache.renderWidth = engine.getRenderWidth();
  22626. this._cache.renderHeight = engine.getRenderHeight();
  22627. }
  22628. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22629. return this._projectionMatrix;
  22630. };
  22631. Camera.prototype.getTranformationMatrix = function () {
  22632. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22633. return this._transformMatrix;
  22634. };
  22635. Camera.prototype.updateFrustumPlanes = function () {
  22636. if (!this._refreshFrustumPlanes) {
  22637. return;
  22638. }
  22639. this.getTranformationMatrix();
  22640. if (!this._frustumPlanes) {
  22641. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22642. }
  22643. else {
  22644. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22645. }
  22646. this._refreshFrustumPlanes = false;
  22647. };
  22648. Camera.prototype.isInFrustum = function (target) {
  22649. this.updateFrustumPlanes();
  22650. return target.isInFrustum(this._frustumPlanes);
  22651. };
  22652. Camera.prototype.isCompletelyInFrustum = function (target) {
  22653. this.updateFrustumPlanes();
  22654. return target.isCompletelyInFrustum(this._frustumPlanes);
  22655. };
  22656. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22657. if (length === void 0) { length = 100; }
  22658. if (!transform) {
  22659. transform = this.getWorldMatrix();
  22660. }
  22661. if (!origin) {
  22662. origin = this.position;
  22663. }
  22664. var forward = new BABYLON.Vector3(0, 0, 1);
  22665. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22666. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22667. return new BABYLON.Ray(origin, direction, length);
  22668. };
  22669. /**
  22670. * Releases resources associated with this node.
  22671. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22672. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22673. */
  22674. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22675. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22676. // Observables
  22677. this.onViewMatrixChangedObservable.clear();
  22678. this.onProjectionMatrixChangedObservable.clear();
  22679. this.onAfterCheckInputsObservable.clear();
  22680. this.onRestoreStateObservable.clear();
  22681. // Inputs
  22682. if (this.inputs) {
  22683. this.inputs.clear();
  22684. }
  22685. // Animations
  22686. this.getScene().stopAnimation(this);
  22687. // Remove from scene
  22688. this.getScene().removeCamera(this);
  22689. while (this._rigCameras.length > 0) {
  22690. var camera = this._rigCameras.pop();
  22691. if (camera) {
  22692. camera.dispose();
  22693. }
  22694. }
  22695. // Postprocesses
  22696. if (this._rigPostProcess) {
  22697. this._rigPostProcess.dispose(this);
  22698. this._rigPostProcess = null;
  22699. this._postProcesses = [];
  22700. }
  22701. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22702. this._rigPostProcess = null;
  22703. this._postProcesses = [];
  22704. }
  22705. else {
  22706. var i = this._postProcesses.length;
  22707. while (--i >= 0) {
  22708. var postProcess = this._postProcesses[i];
  22709. if (postProcess) {
  22710. postProcess.dispose(this);
  22711. }
  22712. }
  22713. }
  22714. // Render targets
  22715. var i = this.customRenderTargets.length;
  22716. while (--i >= 0) {
  22717. this.customRenderTargets[i].dispose();
  22718. }
  22719. this.customRenderTargets = [];
  22720. // Active Meshes
  22721. this._activeMeshes.dispose();
  22722. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22723. };
  22724. Object.defineProperty(Camera.prototype, "leftCamera", {
  22725. // ---- Camera rigs section ----
  22726. get: function () {
  22727. if (this._rigCameras.length < 1) {
  22728. return null;
  22729. }
  22730. return this._rigCameras[0];
  22731. },
  22732. enumerable: true,
  22733. configurable: true
  22734. });
  22735. Object.defineProperty(Camera.prototype, "rightCamera", {
  22736. get: function () {
  22737. if (this._rigCameras.length < 2) {
  22738. return null;
  22739. }
  22740. return this._rigCameras[1];
  22741. },
  22742. enumerable: true,
  22743. configurable: true
  22744. });
  22745. Camera.prototype.getLeftTarget = function () {
  22746. if (this._rigCameras.length < 1) {
  22747. return null;
  22748. }
  22749. return this._rigCameras[0].getTarget();
  22750. };
  22751. Camera.prototype.getRightTarget = function () {
  22752. if (this._rigCameras.length < 2) {
  22753. return null;
  22754. }
  22755. return this._rigCameras[1].getTarget();
  22756. };
  22757. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22758. if (this.cameraRigMode === mode) {
  22759. return;
  22760. }
  22761. while (this._rigCameras.length > 0) {
  22762. var camera = this._rigCameras.pop();
  22763. if (camera) {
  22764. camera.dispose();
  22765. }
  22766. }
  22767. this.cameraRigMode = mode;
  22768. this._cameraRigParams = {};
  22769. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22770. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22771. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22772. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22773. // create the rig cameras, unless none
  22774. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22775. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22776. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22777. if (leftCamera && rightCamera) {
  22778. this._rigCameras.push(leftCamera);
  22779. this._rigCameras.push(rightCamera);
  22780. }
  22781. }
  22782. switch (this.cameraRigMode) {
  22783. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22784. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22785. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22786. break;
  22787. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22788. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22789. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22790. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22791. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22792. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22793. break;
  22794. case Camera.RIG_MODE_VR:
  22795. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22796. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22797. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22798. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22799. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22800. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22801. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22802. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22803. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22804. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22805. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22806. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22807. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22808. if (metrics.compensateDistortion) {
  22809. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22810. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22811. }
  22812. break;
  22813. case Camera.RIG_MODE_WEBVR:
  22814. if (rigParams.vrDisplay) {
  22815. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22816. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22817. //Left eye
  22818. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22819. this._rigCameras[0].setCameraRigParameter("left", true);
  22820. //leaving this for future reference
  22821. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22822. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22823. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22824. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22825. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22826. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22827. this._rigCameras[0].parent = this;
  22828. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22829. //Right eye
  22830. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22831. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22832. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22833. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22834. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22835. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22836. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22837. this._rigCameras[1].parent = this;
  22838. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22839. if (Camera.UseAlternateWebVRRendering) {
  22840. this._rigCameras[1]._skipRendering = true;
  22841. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22842. }
  22843. }
  22844. break;
  22845. }
  22846. this._cascadePostProcessesToRigCams();
  22847. this.update();
  22848. };
  22849. Camera.prototype._getVRProjectionMatrix = function () {
  22850. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22851. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22852. return this._projectionMatrix;
  22853. };
  22854. Camera.prototype._updateCameraRotationMatrix = function () {
  22855. //Here for WebVR
  22856. };
  22857. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22858. //Here for WebVR
  22859. };
  22860. /**
  22861. * This function MUST be overwritten by the different WebVR cameras available.
  22862. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22863. */
  22864. Camera.prototype._getWebVRProjectionMatrix = function () {
  22865. return BABYLON.Matrix.Identity();
  22866. };
  22867. /**
  22868. * This function MUST be overwritten by the different WebVR cameras available.
  22869. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22870. */
  22871. Camera.prototype._getWebVRViewMatrix = function () {
  22872. return BABYLON.Matrix.Identity();
  22873. };
  22874. Camera.prototype.setCameraRigParameter = function (name, value) {
  22875. if (!this._cameraRigParams) {
  22876. this._cameraRigParams = {};
  22877. }
  22878. this._cameraRigParams[name] = value;
  22879. //provisionnally:
  22880. if (name === "interaxialDistance") {
  22881. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22882. }
  22883. };
  22884. /**
  22885. * needs to be overridden by children so sub has required properties to be copied
  22886. */
  22887. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22888. return null;
  22889. };
  22890. /**
  22891. * May need to be overridden by children
  22892. */
  22893. Camera.prototype._updateRigCameras = function () {
  22894. for (var i = 0; i < this._rigCameras.length; i++) {
  22895. this._rigCameras[i].minZ = this.minZ;
  22896. this._rigCameras[i].maxZ = this.maxZ;
  22897. this._rigCameras[i].fov = this.fov;
  22898. }
  22899. // only update viewport when ANAGLYPH
  22900. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22901. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22902. }
  22903. };
  22904. Camera.prototype._setupInputs = function () {
  22905. };
  22906. Camera.prototype.serialize = function () {
  22907. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22908. // Type
  22909. serializationObject.type = this.getClassName();
  22910. // Parent
  22911. if (this.parent) {
  22912. serializationObject.parentId = this.parent.id;
  22913. }
  22914. if (this.inputs) {
  22915. this.inputs.serialize(serializationObject);
  22916. }
  22917. // Animations
  22918. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22919. serializationObject.ranges = this.serializeAnimationRanges();
  22920. return serializationObject;
  22921. };
  22922. Camera.prototype.clone = function (name) {
  22923. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22924. };
  22925. Camera.prototype.getDirection = function (localAxis) {
  22926. var result = BABYLON.Vector3.Zero();
  22927. this.getDirectionToRef(localAxis, result);
  22928. return result;
  22929. };
  22930. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22931. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22932. };
  22933. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22934. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22935. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22936. switch (type) {
  22937. case "ArcRotateCamera":
  22938. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22939. case "DeviceOrientationCamera":
  22940. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22941. case "FollowCamera":
  22942. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22943. case "ArcFollowCamera":
  22944. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22945. case "GamepadCamera":
  22946. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22947. case "TouchCamera":
  22948. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22949. case "VirtualJoysticksCamera":
  22950. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22951. case "WebVRFreeCamera":
  22952. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22953. case "WebVRGamepadCamera":
  22954. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22955. case "VRDeviceOrientationFreeCamera":
  22956. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22957. case "VRDeviceOrientationGamepadCamera":
  22958. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22959. case "AnaglyphArcRotateCamera":
  22960. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22961. case "AnaglyphFreeCamera":
  22962. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22963. case "AnaglyphGamepadCamera":
  22964. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22965. case "AnaglyphUniversalCamera":
  22966. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22967. case "StereoscopicArcRotateCamera":
  22968. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22969. case "StereoscopicFreeCamera":
  22970. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22971. case "StereoscopicGamepadCamera":
  22972. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22973. case "StereoscopicUniversalCamera":
  22974. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22975. case "FreeCamera": // Forcing Universal here
  22976. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22977. default: // Universal Camera is the default value
  22978. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22979. }
  22980. };
  22981. Camera.prototype.computeWorldMatrix = function () {
  22982. return this.getWorldMatrix();
  22983. };
  22984. Camera.Parse = function (parsedCamera, scene) {
  22985. var type = parsedCamera.type;
  22986. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22987. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22988. // Parent
  22989. if (parsedCamera.parentId) {
  22990. camera._waitingParentId = parsedCamera.parentId;
  22991. }
  22992. //If camera has an input manager, let it parse inputs settings
  22993. if (camera.inputs) {
  22994. camera.inputs.parse(parsedCamera);
  22995. camera._setupInputs();
  22996. }
  22997. if (camera.setPosition) { // need to force position
  22998. camera.position.copyFromFloats(0, 0, 0);
  22999. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23000. }
  23001. // Target
  23002. if (parsedCamera.target) {
  23003. if (camera.setTarget) {
  23004. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23005. }
  23006. }
  23007. // Apply 3d rig, when found
  23008. if (parsedCamera.cameraRigMode) {
  23009. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23010. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23011. }
  23012. // Animations
  23013. if (parsedCamera.animations) {
  23014. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23015. var parsedAnimation = parsedCamera.animations[animationIndex];
  23016. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23017. }
  23018. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23019. }
  23020. if (parsedCamera.autoAnimate) {
  23021. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23022. }
  23023. return camera;
  23024. };
  23025. // Statics
  23026. Camera._PERSPECTIVE_CAMERA = 0;
  23027. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23028. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23029. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23030. Camera._RIG_MODE_NONE = 0;
  23031. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23032. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23033. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23034. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23035. Camera._RIG_MODE_VR = 20;
  23036. Camera._RIG_MODE_WEBVR = 21;
  23037. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23038. Camera.UseAlternateWebVRRendering = false;
  23039. __decorate([
  23040. BABYLON.serializeAsVector3()
  23041. ], Camera.prototype, "position", void 0);
  23042. __decorate([
  23043. BABYLON.serializeAsVector3()
  23044. ], Camera.prototype, "upVector", void 0);
  23045. __decorate([
  23046. BABYLON.serialize()
  23047. ], Camera.prototype, "orthoLeft", void 0);
  23048. __decorate([
  23049. BABYLON.serialize()
  23050. ], Camera.prototype, "orthoRight", void 0);
  23051. __decorate([
  23052. BABYLON.serialize()
  23053. ], Camera.prototype, "orthoBottom", void 0);
  23054. __decorate([
  23055. BABYLON.serialize()
  23056. ], Camera.prototype, "orthoTop", void 0);
  23057. __decorate([
  23058. BABYLON.serialize()
  23059. ], Camera.prototype, "fov", void 0);
  23060. __decorate([
  23061. BABYLON.serialize()
  23062. ], Camera.prototype, "minZ", void 0);
  23063. __decorate([
  23064. BABYLON.serialize()
  23065. ], Camera.prototype, "maxZ", void 0);
  23066. __decorate([
  23067. BABYLON.serialize()
  23068. ], Camera.prototype, "inertia", void 0);
  23069. __decorate([
  23070. BABYLON.serialize()
  23071. ], Camera.prototype, "mode", void 0);
  23072. __decorate([
  23073. BABYLON.serialize()
  23074. ], Camera.prototype, "layerMask", void 0);
  23075. __decorate([
  23076. BABYLON.serialize()
  23077. ], Camera.prototype, "fovMode", void 0);
  23078. __decorate([
  23079. BABYLON.serialize()
  23080. ], Camera.prototype, "cameraRigMode", void 0);
  23081. __decorate([
  23082. BABYLON.serialize()
  23083. ], Camera.prototype, "interaxialDistance", void 0);
  23084. __decorate([
  23085. BABYLON.serialize()
  23086. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23087. return Camera;
  23088. }(BABYLON.Node));
  23089. BABYLON.Camera = Camera;
  23090. })(BABYLON || (BABYLON = {}));
  23091. //# sourceMappingURL=babylon.camera.js.map
  23092. var BABYLON;
  23093. (function (BABYLON) {
  23094. var RenderingManager = /** @class */ (function () {
  23095. function RenderingManager(scene) {
  23096. this._renderingGroups = new Array();
  23097. this._autoClearDepthStencil = {};
  23098. this._customOpaqueSortCompareFn = {};
  23099. this._customAlphaTestSortCompareFn = {};
  23100. this._customTransparentSortCompareFn = {};
  23101. this._renderinGroupInfo = null;
  23102. this._scene = scene;
  23103. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23104. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23105. }
  23106. }
  23107. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23108. if (depth === void 0) { depth = true; }
  23109. if (stencil === void 0) { stencil = true; }
  23110. if (this._depthStencilBufferAlreadyCleaned) {
  23111. return;
  23112. }
  23113. this._scene.getEngine().clear(null, false, depth, stencil);
  23114. this._depthStencilBufferAlreadyCleaned = true;
  23115. };
  23116. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23117. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23118. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23119. var info = null;
  23120. if (observable) {
  23121. if (!this._renderinGroupInfo) {
  23122. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23123. }
  23124. info = this._renderinGroupInfo;
  23125. info.scene = this._scene;
  23126. info.camera = this._scene.activeCamera;
  23127. }
  23128. // Dispatch sprites
  23129. if (renderSprites) {
  23130. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23131. var manager = this._scene.spriteManagers[index];
  23132. this.dispatchSprites(manager);
  23133. }
  23134. }
  23135. // Render
  23136. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23137. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23138. var renderingGroup = this._renderingGroups[index];
  23139. if (!renderingGroup && !observable)
  23140. continue;
  23141. var renderingGroupMask = 0;
  23142. // Fire PRECLEAR stage
  23143. if (observable && info) {
  23144. renderingGroupMask = Math.pow(2, index);
  23145. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23146. info.renderingGroupId = index;
  23147. observable.notifyObservers(info, renderingGroupMask);
  23148. }
  23149. // Clear depth/stencil if needed
  23150. if (RenderingManager.AUTOCLEAR) {
  23151. var autoClear = this._autoClearDepthStencil[index];
  23152. if (autoClear && autoClear.autoClear) {
  23153. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23154. }
  23155. }
  23156. if (observable && info) {
  23157. // Fire PREOPAQUE stage
  23158. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23159. observable.notifyObservers(info, renderingGroupMask);
  23160. // Fire PRETRANSPARENT stage
  23161. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23162. observable.notifyObservers(info, renderingGroupMask);
  23163. }
  23164. if (renderingGroup)
  23165. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23166. // Fire POSTTRANSPARENT stage
  23167. if (observable && info) {
  23168. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23169. observable.notifyObservers(info, renderingGroupMask);
  23170. }
  23171. }
  23172. };
  23173. RenderingManager.prototype.reset = function () {
  23174. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23175. var renderingGroup = this._renderingGroups[index];
  23176. if (renderingGroup) {
  23177. renderingGroup.prepare();
  23178. }
  23179. }
  23180. };
  23181. RenderingManager.prototype.dispose = function () {
  23182. this.freeRenderingGroups();
  23183. this._renderingGroups.length = 0;
  23184. };
  23185. /**
  23186. * Clear the info related to rendering groups preventing retention points during dispose.
  23187. */
  23188. RenderingManager.prototype.freeRenderingGroups = function () {
  23189. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23190. var renderingGroup = this._renderingGroups[index];
  23191. if (renderingGroup) {
  23192. renderingGroup.dispose();
  23193. }
  23194. }
  23195. };
  23196. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23197. if (this._renderingGroups[renderingGroupId] === undefined) {
  23198. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23199. }
  23200. };
  23201. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23202. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23203. this._prepareRenderingGroup(renderingGroupId);
  23204. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23205. };
  23206. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23207. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23208. this._prepareRenderingGroup(renderingGroupId);
  23209. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23210. };
  23211. /**
  23212. * @param subMesh The submesh to dispatch
  23213. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23214. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23215. */
  23216. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23217. if (mesh === undefined) {
  23218. mesh = subMesh.getMesh();
  23219. }
  23220. var renderingGroupId = mesh.renderingGroupId || 0;
  23221. this._prepareRenderingGroup(renderingGroupId);
  23222. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23223. };
  23224. /**
  23225. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23226. * This allowed control for front to back rendering or reversly depending of the special needs.
  23227. *
  23228. * @param renderingGroupId The rendering group id corresponding to its index
  23229. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23230. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23231. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23232. */
  23233. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23234. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23235. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23236. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23237. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23238. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23239. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23240. if (this._renderingGroups[renderingGroupId]) {
  23241. var group = this._renderingGroups[renderingGroupId];
  23242. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23243. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23244. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23245. }
  23246. };
  23247. /**
  23248. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23249. *
  23250. * @param renderingGroupId The rendering group id corresponding to its index
  23251. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23252. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23253. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23254. */
  23255. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23256. if (depth === void 0) { depth = true; }
  23257. if (stencil === void 0) { stencil = true; }
  23258. this._autoClearDepthStencil[renderingGroupId] = {
  23259. autoClear: autoClearDepthStencil,
  23260. depth: depth,
  23261. stencil: stencil
  23262. };
  23263. };
  23264. /**
  23265. * The max id used for rendering groups (not included)
  23266. */
  23267. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23268. /**
  23269. * The min id used for rendering groups (included)
  23270. */
  23271. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23272. /**
  23273. * Used to globally prevent autoclearing scenes.
  23274. */
  23275. RenderingManager.AUTOCLEAR = true;
  23276. return RenderingManager;
  23277. }());
  23278. BABYLON.RenderingManager = RenderingManager;
  23279. })(BABYLON || (BABYLON = {}));
  23280. //# sourceMappingURL=babylon.renderingManager.js.map
  23281. var BABYLON;
  23282. (function (BABYLON) {
  23283. var RenderingGroup = /** @class */ (function () {
  23284. /**
  23285. * Creates a new rendering group.
  23286. * @param index The rendering group index
  23287. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23288. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23289. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23290. */
  23291. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23292. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23293. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23294. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23295. this.index = index;
  23296. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23297. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23298. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23299. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23300. this._particleSystems = new BABYLON.SmartArray(256);
  23301. this._spriteManagers = new BABYLON.SmartArray(256);
  23302. this._edgesRenderers = new BABYLON.SmartArray(16);
  23303. this._scene = scene;
  23304. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23305. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23306. this.transparentSortCompareFn = transparentSortCompareFn;
  23307. }
  23308. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23309. /**
  23310. * Set the opaque sort comparison function.
  23311. * If null the sub meshes will be render in the order they were created
  23312. */
  23313. set: function (value) {
  23314. this._opaqueSortCompareFn = value;
  23315. if (value) {
  23316. this._renderOpaque = this.renderOpaqueSorted;
  23317. }
  23318. else {
  23319. this._renderOpaque = RenderingGroup.renderUnsorted;
  23320. }
  23321. },
  23322. enumerable: true,
  23323. configurable: true
  23324. });
  23325. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23326. /**
  23327. * Set the alpha test sort comparison function.
  23328. * If null the sub meshes will be render in the order they were created
  23329. */
  23330. set: function (value) {
  23331. this._alphaTestSortCompareFn = value;
  23332. if (value) {
  23333. this._renderAlphaTest = this.renderAlphaTestSorted;
  23334. }
  23335. else {
  23336. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23337. }
  23338. },
  23339. enumerable: true,
  23340. configurable: true
  23341. });
  23342. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23343. /**
  23344. * Set the transparent sort comparison function.
  23345. * If null the sub meshes will be render in the order they were created
  23346. */
  23347. set: function (value) {
  23348. if (value) {
  23349. this._transparentSortCompareFn = value;
  23350. }
  23351. else {
  23352. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23353. }
  23354. this._renderTransparent = this.renderTransparentSorted;
  23355. },
  23356. enumerable: true,
  23357. configurable: true
  23358. });
  23359. /**
  23360. * Render all the sub meshes contained in the group.
  23361. * @param customRenderFunction Used to override the default render behaviour of the group.
  23362. * @returns true if rendered some submeshes.
  23363. */
  23364. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23365. if (customRenderFunction) {
  23366. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23367. return;
  23368. }
  23369. var engine = this._scene.getEngine();
  23370. // Depth only
  23371. if (this._depthOnlySubMeshes.length !== 0) {
  23372. engine.setColorWrite(false);
  23373. this._renderAlphaTest(this._depthOnlySubMeshes);
  23374. engine.setColorWrite(true);
  23375. }
  23376. // Opaque
  23377. if (this._opaqueSubMeshes.length !== 0) {
  23378. this._renderOpaque(this._opaqueSubMeshes);
  23379. }
  23380. // Alpha test
  23381. if (this._alphaTestSubMeshes.length !== 0) {
  23382. this._renderAlphaTest(this._alphaTestSubMeshes);
  23383. }
  23384. var stencilState = engine.getStencilBuffer();
  23385. engine.setStencilBuffer(false);
  23386. // Sprites
  23387. if (renderSprites) {
  23388. this._renderSprites();
  23389. }
  23390. // Particles
  23391. if (renderParticles) {
  23392. this._renderParticles(activeMeshes);
  23393. }
  23394. if (this.onBeforeTransparentRendering) {
  23395. this.onBeforeTransparentRendering();
  23396. }
  23397. // Transparent
  23398. if (this._transparentSubMeshes.length !== 0) {
  23399. this._renderTransparent(this._transparentSubMeshes);
  23400. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23401. }
  23402. // Set back stencil to false in case it changes before the edge renderer.
  23403. engine.setStencilBuffer(false);
  23404. // Edges
  23405. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23406. this._edgesRenderers.data[edgesRendererIndex].render();
  23407. }
  23408. // Restore Stencil state.
  23409. engine.setStencilBuffer(stencilState);
  23410. };
  23411. /**
  23412. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23413. * @param subMeshes The submeshes to render
  23414. */
  23415. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23416. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23417. };
  23418. /**
  23419. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23420. * @param subMeshes The submeshes to render
  23421. */
  23422. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23423. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23424. };
  23425. /**
  23426. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23427. * @param subMeshes The submeshes to render
  23428. */
  23429. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23430. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23431. };
  23432. /**
  23433. * Renders the submeshes in a specified order.
  23434. * @param subMeshes The submeshes to sort before render
  23435. * @param sortCompareFn The comparison function use to sort
  23436. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23437. * @param transparent Specifies to activate blending if true
  23438. */
  23439. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23440. var subIndex = 0;
  23441. var subMesh;
  23442. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23443. for (; subIndex < subMeshes.length; subIndex++) {
  23444. subMesh = subMeshes.data[subIndex];
  23445. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23446. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23447. }
  23448. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23449. if (sortCompareFn) {
  23450. sortedArray.sort(sortCompareFn);
  23451. }
  23452. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23453. subMesh = sortedArray[subIndex];
  23454. if (transparent) {
  23455. var material = subMesh.getMaterial();
  23456. if (material && material.needDepthPrePass) {
  23457. var engine = material.getScene().getEngine();
  23458. engine.setColorWrite(false);
  23459. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23460. subMesh.render(false);
  23461. engine.setColorWrite(true);
  23462. }
  23463. }
  23464. subMesh.render(transparent);
  23465. }
  23466. };
  23467. /**
  23468. * Renders the submeshes in the order they were dispatched (no sort applied).
  23469. * @param subMeshes The submeshes to render
  23470. */
  23471. RenderingGroup.renderUnsorted = function (subMeshes) {
  23472. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23473. var submesh = subMeshes.data[subIndex];
  23474. submesh.render(false);
  23475. }
  23476. };
  23477. /**
  23478. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23479. * are rendered back to front if in the same alpha index.
  23480. *
  23481. * @param a The first submesh
  23482. * @param b The second submesh
  23483. * @returns The result of the comparison
  23484. */
  23485. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23486. // Alpha index first
  23487. if (a._alphaIndex > b._alphaIndex) {
  23488. return 1;
  23489. }
  23490. if (a._alphaIndex < b._alphaIndex) {
  23491. return -1;
  23492. }
  23493. // Then distance to camera
  23494. return RenderingGroup.backToFrontSortCompare(a, b);
  23495. };
  23496. /**
  23497. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23498. * are rendered back to front.
  23499. *
  23500. * @param a The first submesh
  23501. * @param b The second submesh
  23502. * @returns The result of the comparison
  23503. */
  23504. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23505. // Then distance to camera
  23506. if (a._distanceToCamera < b._distanceToCamera) {
  23507. return 1;
  23508. }
  23509. if (a._distanceToCamera > b._distanceToCamera) {
  23510. return -1;
  23511. }
  23512. return 0;
  23513. };
  23514. /**
  23515. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23516. * are rendered front to back (prevent overdraw).
  23517. *
  23518. * @param a The first submesh
  23519. * @param b The second submesh
  23520. * @returns The result of the comparison
  23521. */
  23522. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23523. // Then distance to camera
  23524. if (a._distanceToCamera < b._distanceToCamera) {
  23525. return -1;
  23526. }
  23527. if (a._distanceToCamera > b._distanceToCamera) {
  23528. return 1;
  23529. }
  23530. return 0;
  23531. };
  23532. /**
  23533. * Resets the different lists of submeshes to prepare a new frame.
  23534. */
  23535. RenderingGroup.prototype.prepare = function () {
  23536. this._opaqueSubMeshes.reset();
  23537. this._transparentSubMeshes.reset();
  23538. this._alphaTestSubMeshes.reset();
  23539. this._depthOnlySubMeshes.reset();
  23540. this._particleSystems.reset();
  23541. this._spriteManagers.reset();
  23542. this._edgesRenderers.reset();
  23543. };
  23544. RenderingGroup.prototype.dispose = function () {
  23545. this._opaqueSubMeshes.dispose();
  23546. this._transparentSubMeshes.dispose();
  23547. this._alphaTestSubMeshes.dispose();
  23548. this._depthOnlySubMeshes.dispose();
  23549. this._particleSystems.dispose();
  23550. this._spriteManagers.dispose();
  23551. this._edgesRenderers.dispose();
  23552. };
  23553. /**
  23554. * Inserts the submesh in its correct queue depending on its material.
  23555. * @param subMesh The submesh to dispatch
  23556. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23557. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23558. */
  23559. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23560. // Get mesh and materials if not provided
  23561. if (mesh === undefined) {
  23562. mesh = subMesh.getMesh();
  23563. }
  23564. if (material === undefined) {
  23565. material = subMesh.getMaterial();
  23566. }
  23567. if (material === null || material === undefined) {
  23568. return;
  23569. }
  23570. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23571. this._transparentSubMeshes.push(subMesh);
  23572. }
  23573. else if (material.needAlphaTesting()) { // Alpha test
  23574. if (material.needDepthPrePass) {
  23575. this._depthOnlySubMeshes.push(subMesh);
  23576. }
  23577. this._alphaTestSubMeshes.push(subMesh);
  23578. }
  23579. else {
  23580. if (material.needDepthPrePass) {
  23581. this._depthOnlySubMeshes.push(subMesh);
  23582. }
  23583. this._opaqueSubMeshes.push(subMesh); // Opaque
  23584. }
  23585. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23586. this._edgesRenderers.push(mesh._edgesRenderer);
  23587. }
  23588. };
  23589. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23590. this._spriteManagers.push(spriteManager);
  23591. };
  23592. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23593. this._particleSystems.push(particleSystem);
  23594. };
  23595. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23596. if (this._particleSystems.length === 0) {
  23597. return;
  23598. }
  23599. // Particles
  23600. var activeCamera = this._scene.activeCamera;
  23601. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23602. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23603. var particleSystem = this._particleSystems.data[particleIndex];
  23604. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23605. continue;
  23606. }
  23607. var emitter = particleSystem.emitter;
  23608. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23609. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23610. }
  23611. }
  23612. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23613. };
  23614. RenderingGroup.prototype._renderSprites = function () {
  23615. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23616. return;
  23617. }
  23618. // Sprites
  23619. var activeCamera = this._scene.activeCamera;
  23620. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23621. for (var id = 0; id < this._spriteManagers.length; id++) {
  23622. var spriteManager = this._spriteManagers.data[id];
  23623. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23624. spriteManager.render();
  23625. }
  23626. }
  23627. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23628. };
  23629. return RenderingGroup;
  23630. }());
  23631. BABYLON.RenderingGroup = RenderingGroup;
  23632. })(BABYLON || (BABYLON = {}));
  23633. //# sourceMappingURL=babylon.renderingGroup.js.map
  23634. var BABYLON;
  23635. (function (BABYLON) {
  23636. /** @hidden */
  23637. var ClickInfo = /** @class */ (function () {
  23638. function ClickInfo() {
  23639. this._singleClick = false;
  23640. this._doubleClick = false;
  23641. this._hasSwiped = false;
  23642. this._ignore = false;
  23643. }
  23644. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23645. get: function () {
  23646. return this._singleClick;
  23647. },
  23648. set: function (b) {
  23649. this._singleClick = b;
  23650. },
  23651. enumerable: true,
  23652. configurable: true
  23653. });
  23654. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23655. get: function () {
  23656. return this._doubleClick;
  23657. },
  23658. set: function (b) {
  23659. this._doubleClick = b;
  23660. },
  23661. enumerable: true,
  23662. configurable: true
  23663. });
  23664. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23665. get: function () {
  23666. return this._hasSwiped;
  23667. },
  23668. set: function (b) {
  23669. this._hasSwiped = b;
  23670. },
  23671. enumerable: true,
  23672. configurable: true
  23673. });
  23674. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23675. get: function () {
  23676. return this._ignore;
  23677. },
  23678. set: function (b) {
  23679. this._ignore = b;
  23680. },
  23681. enumerable: true,
  23682. configurable: true
  23683. });
  23684. return ClickInfo;
  23685. }());
  23686. /**
  23687. * This class is used by the onRenderingGroupObservable
  23688. */
  23689. var RenderingGroupInfo = /** @class */ (function () {
  23690. function RenderingGroupInfo() {
  23691. }
  23692. /**
  23693. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23694. * This stage will be fired no matter what
  23695. */
  23696. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23697. /**
  23698. * Called before opaque object are rendered.
  23699. * This stage will be fired only if there's 3D Opaque content to render
  23700. */
  23701. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23702. /**
  23703. * Called after the opaque objects are rendered and before the transparent ones
  23704. * This stage will be fired only if there's 3D transparent content to render
  23705. */
  23706. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23707. /**
  23708. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23709. * This stage will be fired no matter what
  23710. */
  23711. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23712. return RenderingGroupInfo;
  23713. }());
  23714. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23715. /**
  23716. * Represents a scene to be rendered by the engine.
  23717. * @see http://doc.babylonjs.com/features/scene
  23718. */
  23719. var Scene = /** @class */ (function () {
  23720. /**
  23721. * Creates a new Scene
  23722. * @param engine defines the engine to use to render this scene
  23723. */
  23724. function Scene(engine) {
  23725. // Members
  23726. /**
  23727. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23728. */
  23729. this.autoClear = true;
  23730. /**
  23731. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23732. */
  23733. this.autoClearDepthAndStencil = true;
  23734. /**
  23735. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23736. */
  23737. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23738. /**
  23739. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23740. */
  23741. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23742. this._forceWireframe = false;
  23743. this._forcePointsCloud = false;
  23744. /**
  23745. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23746. */
  23747. this.forceShowBoundingBoxes = false;
  23748. /**
  23749. * Gets or sets a boolean indicating if animations are enabled
  23750. */
  23751. this.animationsEnabled = true;
  23752. this._animationPropertiesOverride = null;
  23753. /**
  23754. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23755. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23756. */
  23757. this.useConstantAnimationDeltaTime = false;
  23758. /**
  23759. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23760. * Please note that it requires to run a ray cast through the scene on every frame
  23761. */
  23762. this.constantlyUpdateMeshUnderPointer = false;
  23763. /**
  23764. * Defines the HTML cursor to use when hovering over interactive elements
  23765. */
  23766. this.hoverCursor = "pointer";
  23767. /**
  23768. * Defines the HTML default cursor to use (empty by default)
  23769. */
  23770. this.defaultCursor = "";
  23771. /**
  23772. * This is used to call preventDefault() on pointer down
  23773. * in order to block unwanted artifacts like system double clicks
  23774. */
  23775. this.preventDefaultOnPointerDown = true;
  23776. // Metadata
  23777. /**
  23778. * Gets or sets user defined metadata
  23779. */
  23780. this.metadata = null;
  23781. /**
  23782. * Use this array to add regular expressions used to disable offline support for specific urls
  23783. */
  23784. this.disableOfflineSupportExceptionRules = new Array();
  23785. /**
  23786. * An event triggered when the scene is disposed.
  23787. */
  23788. this.onDisposeObservable = new BABYLON.Observable();
  23789. this._onDisposeObserver = null;
  23790. /**
  23791. * An event triggered before rendering the scene (right after animations and physics)
  23792. */
  23793. this.onBeforeRenderObservable = new BABYLON.Observable();
  23794. this._onBeforeRenderObserver = null;
  23795. /**
  23796. * An event triggered after rendering the scene
  23797. */
  23798. this.onAfterRenderObservable = new BABYLON.Observable();
  23799. this._onAfterRenderObserver = null;
  23800. /**
  23801. * An event triggered before animating the scene
  23802. */
  23803. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23804. /**
  23805. * An event triggered after animations processing
  23806. */
  23807. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23808. /**
  23809. * An event triggered before draw calls are ready to be sent
  23810. */
  23811. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23812. /**
  23813. * An event triggered after draw calls have been sent
  23814. */
  23815. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23816. /**
  23817. * An event triggered when physic simulation is about to be run
  23818. */
  23819. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23820. /**
  23821. * An event triggered when physic simulation has been done
  23822. */
  23823. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23824. /**
  23825. * An event triggered when the scene is ready
  23826. */
  23827. this.onReadyObservable = new BABYLON.Observable();
  23828. /**
  23829. * An event triggered before rendering a camera
  23830. */
  23831. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23832. this._onBeforeCameraRenderObserver = null;
  23833. /**
  23834. * An event triggered after rendering a camera
  23835. */
  23836. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23837. this._onAfterCameraRenderObserver = null;
  23838. /**
  23839. * An event triggered when active meshes evaluation is about to start
  23840. */
  23841. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23842. /**
  23843. * An event triggered when active meshes evaluation is done
  23844. */
  23845. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23846. /**
  23847. * An event triggered when particles rendering is about to start
  23848. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23849. */
  23850. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23851. /**
  23852. * An event triggered when particles rendering is done
  23853. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23854. */
  23855. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23856. /**
  23857. * An event triggered when sprites rendering is about to start
  23858. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23859. */
  23860. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23861. /**
  23862. * An event triggered when sprites rendering is done
  23863. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23864. */
  23865. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23866. /**
  23867. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23868. */
  23869. this.onDataLoadedObservable = new BABYLON.Observable();
  23870. /**
  23871. * An event triggered when a camera is created
  23872. */
  23873. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23874. /**
  23875. * An event triggered when a camera is removed
  23876. */
  23877. this.onCameraRemovedObservable = new BABYLON.Observable();
  23878. /**
  23879. * An event triggered when a light is created
  23880. */
  23881. this.onNewLightAddedObservable = new BABYLON.Observable();
  23882. /**
  23883. * An event triggered when a light is removed
  23884. */
  23885. this.onLightRemovedObservable = new BABYLON.Observable();
  23886. /**
  23887. * An event triggered when a geometry is created
  23888. */
  23889. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23890. /**
  23891. * An event triggered when a geometry is removed
  23892. */
  23893. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23894. /**
  23895. * An event triggered when a transform node is created
  23896. */
  23897. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23898. /**
  23899. * An event triggered when a transform node is removed
  23900. */
  23901. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23902. /**
  23903. * An event triggered when a mesh is created
  23904. */
  23905. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23906. /**
  23907. * An event triggered when a mesh is removed
  23908. */
  23909. this.onMeshRemovedObservable = new BABYLON.Observable();
  23910. /**
  23911. * An event triggered when render targets are about to be rendered
  23912. * Can happen multiple times per frame.
  23913. */
  23914. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23915. /**
  23916. * An event triggered when render targets were rendered.
  23917. * Can happen multiple times per frame.
  23918. */
  23919. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23920. /**
  23921. * An event triggered before calculating deterministic simulation step
  23922. */
  23923. this.onBeforeStepObservable = new BABYLON.Observable();
  23924. /**
  23925. * An event triggered after calculating deterministic simulation step
  23926. */
  23927. this.onAfterStepObservable = new BABYLON.Observable();
  23928. /**
  23929. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23930. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23931. * 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)
  23932. */
  23933. this.onRenderingGroupObservable = new BABYLON.Observable();
  23934. // Animations
  23935. /**
  23936. * Gets a list of Animations associated with the scene
  23937. */
  23938. this.animations = [];
  23939. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23940. /**
  23941. * 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).
  23942. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23943. */
  23944. this.onPrePointerObservable = new BABYLON.Observable();
  23945. /**
  23946. * Observable event triggered each time an input event is received from the rendering canvas
  23947. */
  23948. this.onPointerObservable = new BABYLON.Observable();
  23949. this._meshPickProceed = false;
  23950. this._currentPickResult = null;
  23951. this._previousPickResult = null;
  23952. this._totalPointersPressed = 0;
  23953. this._doubleClickOccured = false;
  23954. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23955. this.cameraToUseForPointers = null;
  23956. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23957. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23958. this._startingPointerTime = 0;
  23959. this._previousStartingPointerTime = 0;
  23960. this._pointerCaptures = {};
  23961. // Deterministic lockstep
  23962. this._timeAccumulator = 0;
  23963. this._currentStepId = 0;
  23964. this._currentInternalStep = 0;
  23965. // Keyboard
  23966. /**
  23967. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23968. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23969. */
  23970. this.onPreKeyboardObservable = new BABYLON.Observable();
  23971. /**
  23972. * Observable event triggered each time an keyboard event is received from the hosting window
  23973. */
  23974. this.onKeyboardObservable = new BABYLON.Observable();
  23975. // Coordinates system
  23976. this._useRightHandedSystem = false;
  23977. // Fog
  23978. this._fogEnabled = true;
  23979. this._fogMode = Scene.FOGMODE_NONE;
  23980. /**
  23981. * Gets or sets the fog color to use
  23982. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23983. */
  23984. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23985. /**
  23986. * Gets or sets the fog density to use
  23987. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23988. */
  23989. this.fogDensity = 0.1;
  23990. /**
  23991. * Gets or sets the fog start distance to use
  23992. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23993. */
  23994. this.fogStart = 0;
  23995. /**
  23996. * Gets or sets the fog end distance to use
  23997. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23998. */
  23999. this.fogEnd = 1000.0;
  24000. // Lights
  24001. this._shadowsEnabled = true;
  24002. this._lightsEnabled = true;
  24003. /**
  24004. * All of the lights added to this scene
  24005. * @see http://doc.babylonjs.com/babylon101/lights
  24006. */
  24007. this.lights = new Array();
  24008. // Cameras
  24009. /** All of the cameras added to this scene.
  24010. * @see http://doc.babylonjs.com/babylon101/cameras
  24011. */
  24012. this.cameras = new Array();
  24013. /** All of the active cameras added to this scene. */
  24014. this.activeCameras = new Array();
  24015. // Meshes
  24016. /**
  24017. * All of the tranform nodes added to this scene
  24018. * @see http://doc.babylonjs.com/how_to/transformnode
  24019. */
  24020. this.transformNodes = new Array();
  24021. /**
  24022. * All of the (abstract) meshes added to this scene
  24023. */
  24024. this.meshes = new Array();
  24025. /**
  24026. * All of the animation groups added to this scene
  24027. * @see http://doc.babylonjs.com/how_to/group
  24028. */
  24029. this.animationGroups = new Array();
  24030. // Geometries
  24031. this._geometries = new Array();
  24032. /**
  24033. * All of the materials added to this scene
  24034. * @see http://doc.babylonjs.com/babylon101/materials
  24035. */
  24036. this.materials = new Array();
  24037. /**
  24038. * All of the multi-materials added to this scene
  24039. * @see http://doc.babylonjs.com/how_to/multi_materials
  24040. */
  24041. this.multiMaterials = new Array();
  24042. // Textures
  24043. this._texturesEnabled = true;
  24044. /**
  24045. * All of the textures added to this scene
  24046. */
  24047. this.textures = new Array();
  24048. // Particles
  24049. /**
  24050. * Gets or sets a boolean indicating if particles are enabled on this scene
  24051. */
  24052. this.particlesEnabled = true;
  24053. /**
  24054. * All of the particle systems added to this scene
  24055. * @see http://doc.babylonjs.com/babylon101/particles
  24056. */
  24057. this.particleSystems = new Array();
  24058. // Sprites
  24059. /**
  24060. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24061. */
  24062. this.spritesEnabled = true;
  24063. /**
  24064. * All of the sprite managers added to this scene
  24065. * @see http://doc.babylonjs.com/babylon101/sprites
  24066. */
  24067. this.spriteManagers = new Array();
  24068. /**
  24069. * The list of layers (background and foreground) of the scene
  24070. */
  24071. this.layers = new Array();
  24072. /**
  24073. * The list of effect layers (highlights/glow) added to the scene
  24074. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24075. * @see http://doc.babylonjs.com/how_to/glow_layer
  24076. */
  24077. this.effectLayers = new Array();
  24078. // Skeletons
  24079. this._skeletonsEnabled = true;
  24080. /**
  24081. * The list of skeletons added to the scene
  24082. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24083. */
  24084. this.skeletons = new Array();
  24085. // Morph targets
  24086. /**
  24087. * The list of morph target managers added to the scene
  24088. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24089. */
  24090. this.morphTargetManagers = new Array();
  24091. // Lens flares
  24092. /**
  24093. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24094. */
  24095. this.lensFlaresEnabled = true;
  24096. /**
  24097. * The list of lens flare system added to the scene
  24098. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24099. */
  24100. this.lensFlareSystems = new Array();
  24101. // Collisions
  24102. /**
  24103. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24104. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24105. */
  24106. this.collisionsEnabled = true;
  24107. /**
  24108. * Defines the gravity applied to this scene (used only for collisions)
  24109. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24110. */
  24111. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24112. // Postprocesses
  24113. /**
  24114. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24115. */
  24116. this.postProcessesEnabled = true;
  24117. /**
  24118. * The list of postprocesses added to the scene
  24119. */
  24120. this.postProcesses = new Array();
  24121. // Customs render targets
  24122. /**
  24123. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24124. */
  24125. this.renderTargetsEnabled = true;
  24126. /**
  24127. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24128. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24129. */
  24130. this.dumpNextRenderTargets = false;
  24131. /**
  24132. * The list of user defined render targets added to the scene
  24133. */
  24134. this.customRenderTargets = new Array();
  24135. /**
  24136. * Gets the list of meshes imported to the scene through SceneLoader
  24137. */
  24138. this.importedMeshesFiles = new Array();
  24139. // Probes
  24140. /**
  24141. * Gets or sets a boolean indicating if probes are enabled on this scene
  24142. */
  24143. this.probesEnabled = true;
  24144. /**
  24145. * The list of reflection probes added to the scene
  24146. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24147. */
  24148. this.reflectionProbes = new Array();
  24149. /** @hidden */
  24150. this._actionManagers = new Array();
  24151. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24152. // Procedural textures
  24153. /**
  24154. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24155. */
  24156. this.proceduralTexturesEnabled = true;
  24157. /**
  24158. * The list of procedural textures added to the scene
  24159. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24160. */
  24161. this.proceduralTextures = new Array();
  24162. /**
  24163. * The list of sound tracks added to the scene
  24164. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24165. */
  24166. this.soundTracks = new Array();
  24167. this._audioEnabled = true;
  24168. this._headphone = false;
  24169. // Performance counters
  24170. this._totalVertices = new BABYLON.PerfCounter();
  24171. /** @hidden */
  24172. this._activeIndices = new BABYLON.PerfCounter();
  24173. /** @hidden */
  24174. this._activeParticles = new BABYLON.PerfCounter();
  24175. /** @hidden */
  24176. this._activeBones = new BABYLON.PerfCounter();
  24177. this._animationTime = 0;
  24178. /**
  24179. * Gets or sets a general scale for animation speed
  24180. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24181. */
  24182. this.animationTimeScale = 1;
  24183. this._renderId = 0;
  24184. this._executeWhenReadyTimeoutId = -1;
  24185. this._intermediateRendering = false;
  24186. this._viewUpdateFlag = -1;
  24187. this._projectionUpdateFlag = -1;
  24188. this._alternateViewUpdateFlag = -1;
  24189. this._alternateProjectionUpdateFlag = -1;
  24190. /** @hidden */
  24191. this._toBeDisposed = new BABYLON.SmartArray(256);
  24192. this._activeRequests = new Array();
  24193. this._pendingData = new Array();
  24194. this._isDisposed = false;
  24195. /**
  24196. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24197. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24198. */
  24199. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24200. this._activeMeshes = new BABYLON.SmartArray(256);
  24201. this._processedMaterials = new BABYLON.SmartArray(256);
  24202. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24203. /** @hidden */
  24204. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24205. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24206. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24207. /** @hidden */
  24208. this._activeAnimatables = new Array();
  24209. this._transformMatrix = BABYLON.Matrix.Zero();
  24210. this._useAlternateCameraConfiguration = false;
  24211. this._alternateRendering = false;
  24212. /**
  24213. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24214. * This is useful if there are more lights that the maximum simulteanous authorized
  24215. */
  24216. this.requireLightSorting = false;
  24217. this._depthRenderer = {};
  24218. this._activeMeshesFrozen = false;
  24219. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24220. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24221. this._engine.scenes.push(this);
  24222. this._uid = null;
  24223. this._renderingManager = new BABYLON.RenderingManager(this);
  24224. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24225. if (BABYLON.OutlineRenderer) {
  24226. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24227. }
  24228. if (BABYLON.Tools.IsWindowObjectExist()) {
  24229. this.attachControl();
  24230. }
  24231. //simplification queue
  24232. if (BABYLON.SimplificationQueue) {
  24233. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24234. }
  24235. //collision coordinator initialization. For now legacy per default.
  24236. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24237. // Uniform Buffer
  24238. this._createUbo();
  24239. // Default Image processing definition.
  24240. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24241. }
  24242. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24243. /** The fog is deactivated */
  24244. get: function () {
  24245. return Scene._FOGMODE_NONE;
  24246. },
  24247. enumerable: true,
  24248. configurable: true
  24249. });
  24250. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24251. /** The fog density is following an exponential function */
  24252. get: function () {
  24253. return Scene._FOGMODE_EXP;
  24254. },
  24255. enumerable: true,
  24256. configurable: true
  24257. });
  24258. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24259. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24260. get: function () {
  24261. return Scene._FOGMODE_EXP2;
  24262. },
  24263. enumerable: true,
  24264. configurable: true
  24265. });
  24266. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24267. /** The fog density is following a linear function. */
  24268. get: function () {
  24269. return Scene._FOGMODE_LINEAR;
  24270. },
  24271. enumerable: true,
  24272. configurable: true
  24273. });
  24274. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24275. /**
  24276. * Texture used in all pbr material as the reflection texture.
  24277. * As in the majority of the scene they are the same (exception for multi room and so on),
  24278. * this is easier to reference from here than from all the materials.
  24279. */
  24280. get: function () {
  24281. return this._environmentTexture;
  24282. },
  24283. /**
  24284. * Texture used in all pbr material as the reflection texture.
  24285. * As in the majority of the scene they are the same (exception for multi room and so on),
  24286. * this is easier to set here than in all the materials.
  24287. */
  24288. set: function (value) {
  24289. if (this._environmentTexture === value) {
  24290. return;
  24291. }
  24292. this._environmentTexture = value;
  24293. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24294. },
  24295. enumerable: true,
  24296. configurable: true
  24297. });
  24298. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24299. /**
  24300. * Default image processing configuration used either in the rendering
  24301. * Forward main pass or through the imageProcessingPostProcess if present.
  24302. * As in the majority of the scene they are the same (exception for multi camera),
  24303. * this is easier to reference from here than from all the materials and post process.
  24304. *
  24305. * No setter as we it is a shared configuration, you can set the values instead.
  24306. */
  24307. get: function () {
  24308. return this._imageProcessingConfiguration;
  24309. },
  24310. enumerable: true,
  24311. configurable: true
  24312. });
  24313. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24314. get: function () {
  24315. return this._forceWireframe;
  24316. },
  24317. /**
  24318. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24319. */
  24320. set: function (value) {
  24321. if (this._forceWireframe === value) {
  24322. return;
  24323. }
  24324. this._forceWireframe = value;
  24325. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24326. },
  24327. enumerable: true,
  24328. configurable: true
  24329. });
  24330. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24331. get: function () {
  24332. return this._forcePointsCloud;
  24333. },
  24334. /**
  24335. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24336. */
  24337. set: function (value) {
  24338. if (this._forcePointsCloud === value) {
  24339. return;
  24340. }
  24341. this._forcePointsCloud = value;
  24342. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24343. },
  24344. enumerable: true,
  24345. configurable: true
  24346. });
  24347. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24348. /**
  24349. * Gets or sets the animation properties override
  24350. */
  24351. get: function () {
  24352. return this._animationPropertiesOverride;
  24353. },
  24354. set: function (value) {
  24355. this._animationPropertiesOverride = value;
  24356. },
  24357. enumerable: true,
  24358. configurable: true
  24359. });
  24360. Object.defineProperty(Scene.prototype, "onDispose", {
  24361. /** Sets a function to be executed when this scene is disposed. */
  24362. set: function (callback) {
  24363. if (this._onDisposeObserver) {
  24364. this.onDisposeObservable.remove(this._onDisposeObserver);
  24365. }
  24366. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24367. },
  24368. enumerable: true,
  24369. configurable: true
  24370. });
  24371. Object.defineProperty(Scene.prototype, "beforeRender", {
  24372. /** Sets a function to be executed before rendering this scene */
  24373. set: function (callback) {
  24374. if (this._onBeforeRenderObserver) {
  24375. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24376. }
  24377. if (callback) {
  24378. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24379. }
  24380. },
  24381. enumerable: true,
  24382. configurable: true
  24383. });
  24384. Object.defineProperty(Scene.prototype, "afterRender", {
  24385. /** Sets a function to be executed after rendering this scene */
  24386. set: function (callback) {
  24387. if (this._onAfterRenderObserver) {
  24388. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24389. }
  24390. if (callback) {
  24391. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24392. }
  24393. },
  24394. enumerable: true,
  24395. configurable: true
  24396. });
  24397. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24398. /** Sets a function to be executed before rendering a camera*/
  24399. set: function (callback) {
  24400. if (this._onBeforeCameraRenderObserver) {
  24401. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24402. }
  24403. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24404. },
  24405. enumerable: true,
  24406. configurable: true
  24407. });
  24408. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24409. /** Sets a function to be executed after rendering a camera*/
  24410. set: function (callback) {
  24411. if (this._onAfterCameraRenderObserver) {
  24412. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24413. }
  24414. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24415. },
  24416. enumerable: true,
  24417. configurable: true
  24418. });
  24419. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24420. /**
  24421. * Gets the gamepad manager associated with the scene
  24422. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24423. */
  24424. get: function () {
  24425. if (!this._gamepadManager) {
  24426. this._gamepadManager = new BABYLON.GamepadManager(this);
  24427. }
  24428. return this._gamepadManager;
  24429. },
  24430. enumerable: true,
  24431. configurable: true
  24432. });
  24433. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24434. /**
  24435. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24436. */
  24437. get: function () {
  24438. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24439. },
  24440. enumerable: true,
  24441. configurable: true
  24442. });
  24443. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24444. get: function () {
  24445. return this._useRightHandedSystem;
  24446. },
  24447. /**
  24448. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24449. */
  24450. set: function (value) {
  24451. if (this._useRightHandedSystem === value) {
  24452. return;
  24453. }
  24454. this._useRightHandedSystem = value;
  24455. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24456. },
  24457. enumerable: true,
  24458. configurable: true
  24459. });
  24460. /**
  24461. * Sets the step Id used by deterministic lock step
  24462. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24463. * @param newStepId defines the step Id
  24464. */
  24465. Scene.prototype.setStepId = function (newStepId) {
  24466. this._currentStepId = newStepId;
  24467. };
  24468. ;
  24469. /**
  24470. * Gets the step Id used by deterministic lock step
  24471. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24472. * @returns the step Id
  24473. */
  24474. Scene.prototype.getStepId = function () {
  24475. return this._currentStepId;
  24476. };
  24477. ;
  24478. /**
  24479. * Gets the internal step used by deterministic lock step
  24480. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24481. * @returns the internal step
  24482. */
  24483. Scene.prototype.getInternalStep = function () {
  24484. return this._currentInternalStep;
  24485. };
  24486. ;
  24487. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24488. get: function () {
  24489. return this._fogEnabled;
  24490. },
  24491. /**
  24492. * Gets or sets a boolean indicating if fog is enabled on this scene
  24493. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24494. */
  24495. set: function (value) {
  24496. if (this._fogEnabled === value) {
  24497. return;
  24498. }
  24499. this._fogEnabled = value;
  24500. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Object.defineProperty(Scene.prototype, "fogMode", {
  24506. get: function () {
  24507. return this._fogMode;
  24508. },
  24509. /**
  24510. * Gets or sets the fog mode to use
  24511. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24512. */
  24513. set: function (value) {
  24514. if (this._fogMode === value) {
  24515. return;
  24516. }
  24517. this._fogMode = value;
  24518. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24524. get: function () {
  24525. return this._shadowsEnabled;
  24526. },
  24527. /**
  24528. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24529. */
  24530. set: function (value) {
  24531. if (this._shadowsEnabled === value) {
  24532. return;
  24533. }
  24534. this._shadowsEnabled = value;
  24535. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24536. },
  24537. enumerable: true,
  24538. configurable: true
  24539. });
  24540. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24541. get: function () {
  24542. return this._lightsEnabled;
  24543. },
  24544. /**
  24545. * Gets or sets a boolean indicating if lights are enabled on this scene
  24546. */
  24547. set: function (value) {
  24548. if (this._lightsEnabled === value) {
  24549. return;
  24550. }
  24551. this._lightsEnabled = value;
  24552. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24553. },
  24554. enumerable: true,
  24555. configurable: true
  24556. });
  24557. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24558. /** The default material used on meshes when no material is affected */
  24559. get: function () {
  24560. if (!this._defaultMaterial) {
  24561. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24562. }
  24563. return this._defaultMaterial;
  24564. },
  24565. /** The default material used on meshes when no material is affected */
  24566. set: function (value) {
  24567. this._defaultMaterial = value;
  24568. },
  24569. enumerable: true,
  24570. configurable: true
  24571. });
  24572. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24573. get: function () {
  24574. return this._texturesEnabled;
  24575. },
  24576. /**
  24577. * Gets or sets a boolean indicating if textures are enabled on this scene
  24578. */
  24579. set: function (value) {
  24580. if (this._texturesEnabled === value) {
  24581. return;
  24582. }
  24583. this._texturesEnabled = value;
  24584. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24585. },
  24586. enumerable: true,
  24587. configurable: true
  24588. });
  24589. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24590. get: function () {
  24591. return this._skeletonsEnabled;
  24592. },
  24593. /**
  24594. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24595. */
  24596. set: function (value) {
  24597. if (this._skeletonsEnabled === value) {
  24598. return;
  24599. }
  24600. this._skeletonsEnabled = value;
  24601. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24607. /**
  24608. * Gets the postprocess render pipeline manager
  24609. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24610. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24611. */
  24612. get: function () {
  24613. if (!this._postProcessRenderPipelineManager) {
  24614. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24615. }
  24616. return this._postProcessRenderPipelineManager;
  24617. },
  24618. enumerable: true,
  24619. configurable: true
  24620. });
  24621. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24622. /**
  24623. * Gets the main soundtrack associated with the scene
  24624. */
  24625. get: function () {
  24626. if (!this._mainSoundTrack) {
  24627. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24628. }
  24629. return this._mainSoundTrack;
  24630. },
  24631. enumerable: true,
  24632. configurable: true
  24633. });
  24634. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24635. /** @hidden */
  24636. get: function () {
  24637. return this._alternateRendering;
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24643. /**
  24644. * Gets the list of frustum planes (built from the active camera)
  24645. */
  24646. get: function () {
  24647. return this._frustumPlanes;
  24648. },
  24649. enumerable: true,
  24650. configurable: true
  24651. });
  24652. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24653. /**
  24654. * Gets the current geometry buffer associated to the scene.
  24655. */
  24656. get: function () {
  24657. return this._geometryBufferRenderer;
  24658. },
  24659. /**
  24660. * Sets the current geometry buffer for the scene.
  24661. */
  24662. set: function (geometryBufferRenderer) {
  24663. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24664. this._geometryBufferRenderer = geometryBufferRenderer;
  24665. }
  24666. },
  24667. enumerable: true,
  24668. configurable: true
  24669. });
  24670. Object.defineProperty(Scene.prototype, "debugLayer", {
  24671. /**
  24672. * Gets the debug layer (aka Inspector) associated with the scene
  24673. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24674. */
  24675. get: function () {
  24676. if (!this._debugLayer) {
  24677. this._debugLayer = new BABYLON.DebugLayer(this);
  24678. }
  24679. return this._debugLayer;
  24680. },
  24681. enumerable: true,
  24682. configurable: true
  24683. });
  24684. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24685. /**
  24686. * Gets a boolean indicating if collisions are processed on a web worker
  24687. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24688. */
  24689. get: function () {
  24690. return this._workerCollisions;
  24691. },
  24692. set: function (enabled) {
  24693. if (!BABYLON.CollisionCoordinatorLegacy) {
  24694. return;
  24695. }
  24696. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24697. this._workerCollisions = enabled;
  24698. if (this.collisionCoordinator) {
  24699. this.collisionCoordinator.destroy();
  24700. }
  24701. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24702. this.collisionCoordinator.init(this);
  24703. },
  24704. enumerable: true,
  24705. configurable: true
  24706. });
  24707. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24708. /**
  24709. * Gets the octree used to boost mesh selection (picking)
  24710. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24711. */
  24712. get: function () {
  24713. return this._selectionOctree;
  24714. },
  24715. enumerable: true,
  24716. configurable: true
  24717. });
  24718. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24719. /**
  24720. * Gets the mesh that is currently under the pointer
  24721. */
  24722. get: function () {
  24723. return this._pointerOverMesh;
  24724. },
  24725. enumerable: true,
  24726. configurable: true
  24727. });
  24728. Object.defineProperty(Scene.prototype, "pointerX", {
  24729. /**
  24730. * Gets the current on-screen X position of the pointer
  24731. */
  24732. get: function () {
  24733. return this._pointerX;
  24734. },
  24735. enumerable: true,
  24736. configurable: true
  24737. });
  24738. Object.defineProperty(Scene.prototype, "pointerY", {
  24739. /**
  24740. * Gets the current on-screen Y position of the pointer
  24741. */
  24742. get: function () {
  24743. return this._pointerY;
  24744. },
  24745. enumerable: true,
  24746. configurable: true
  24747. });
  24748. /**
  24749. * Gets the cached material (ie. the latest rendered one)
  24750. * @returns the cached material
  24751. */
  24752. Scene.prototype.getCachedMaterial = function () {
  24753. return this._cachedMaterial;
  24754. };
  24755. /**
  24756. * Gets the cached effect (ie. the latest rendered one)
  24757. * @returns the cached effect
  24758. */
  24759. Scene.prototype.getCachedEffect = function () {
  24760. return this._cachedEffect;
  24761. };
  24762. /**
  24763. * Gets the cached visibility state (ie. the latest rendered one)
  24764. * @returns the cached visibility state
  24765. */
  24766. Scene.prototype.getCachedVisibility = function () {
  24767. return this._cachedVisibility;
  24768. };
  24769. /**
  24770. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24771. * @param material defines the current material
  24772. * @param effect defines the current effect
  24773. * @param visibility defines the current visibility state
  24774. * @returns true if one parameter is not cached
  24775. */
  24776. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24777. if (visibility === void 0) { visibility = 1; }
  24778. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24779. };
  24780. /**
  24781. * Gets the bounding box renderer associated with the scene
  24782. * @returns a BoundingBoxRenderer
  24783. */
  24784. Scene.prototype.getBoundingBoxRenderer = function () {
  24785. if (!this._boundingBoxRenderer) {
  24786. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24787. }
  24788. return this._boundingBoxRenderer;
  24789. };
  24790. /**
  24791. * Gets the outline renderer associated with the scene
  24792. * @returns a OutlineRenderer
  24793. */
  24794. Scene.prototype.getOutlineRenderer = function () {
  24795. return this._outlineRenderer;
  24796. };
  24797. /**
  24798. * Gets the engine associated with the scene
  24799. * @returns an Engine
  24800. */
  24801. Scene.prototype.getEngine = function () {
  24802. return this._engine;
  24803. };
  24804. /**
  24805. * Gets the total number of vertices rendered per frame
  24806. * @returns the total number of vertices rendered per frame
  24807. */
  24808. Scene.prototype.getTotalVertices = function () {
  24809. return this._totalVertices.current;
  24810. };
  24811. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24812. /**
  24813. * Gets the performance counter for total vertices
  24814. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24815. */
  24816. get: function () {
  24817. return this._totalVertices;
  24818. },
  24819. enumerable: true,
  24820. configurable: true
  24821. });
  24822. /**
  24823. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24824. * @returns the total number of active indices rendered per frame
  24825. */
  24826. Scene.prototype.getActiveIndices = function () {
  24827. return this._activeIndices.current;
  24828. };
  24829. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24830. /**
  24831. * Gets the performance counter for active indices
  24832. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24833. */
  24834. get: function () {
  24835. return this._activeIndices;
  24836. },
  24837. enumerable: true,
  24838. configurable: true
  24839. });
  24840. /**
  24841. * Gets the total number of active particles rendered per frame
  24842. * @returns the total number of active particles rendered per frame
  24843. */
  24844. Scene.prototype.getActiveParticles = function () {
  24845. return this._activeParticles.current;
  24846. };
  24847. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24848. /**
  24849. * Gets the performance counter for active particles
  24850. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24851. */
  24852. get: function () {
  24853. return this._activeParticles;
  24854. },
  24855. enumerable: true,
  24856. configurable: true
  24857. });
  24858. /**
  24859. * Gets the total number of active bones rendered per frame
  24860. * @returns the total number of active bones rendered per frame
  24861. */
  24862. Scene.prototype.getActiveBones = function () {
  24863. return this._activeBones.current;
  24864. };
  24865. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24866. /**
  24867. * Gets the performance counter for active bones
  24868. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24869. */
  24870. get: function () {
  24871. return this._activeBones;
  24872. },
  24873. enumerable: true,
  24874. configurable: true
  24875. });
  24876. /** @hidden */
  24877. Scene.prototype.getInterFramePerfCounter = function () {
  24878. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24879. return 0;
  24880. };
  24881. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24882. /** @hidden */
  24883. get: function () {
  24884. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24885. return null;
  24886. },
  24887. enumerable: true,
  24888. configurable: true
  24889. });
  24890. /** @hidden */
  24891. Scene.prototype.getLastFrameDuration = function () {
  24892. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24893. return 0;
  24894. };
  24895. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24896. /** @hidden */
  24897. get: function () {
  24898. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24899. return null;
  24900. },
  24901. enumerable: true,
  24902. configurable: true
  24903. });
  24904. /** @hidden */
  24905. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24906. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24907. return 0;
  24908. };
  24909. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24910. /** @hidden */
  24911. get: function () {
  24912. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24913. return null;
  24914. },
  24915. enumerable: true,
  24916. configurable: true
  24917. });
  24918. /**
  24919. * Gets the array of active meshes
  24920. * @returns an array of AbstractMesh
  24921. */
  24922. Scene.prototype.getActiveMeshes = function () {
  24923. return this._activeMeshes;
  24924. };
  24925. /** @hidden */
  24926. Scene.prototype.getRenderTargetsDuration = function () {
  24927. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24928. return 0;
  24929. };
  24930. /** @hidden */
  24931. Scene.prototype.getRenderDuration = function () {
  24932. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24933. return 0;
  24934. };
  24935. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24936. /** @hidden */
  24937. get: function () {
  24938. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24939. return null;
  24940. },
  24941. enumerable: true,
  24942. configurable: true
  24943. });
  24944. /** @hidden */
  24945. Scene.prototype.getParticlesDuration = function () {
  24946. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24947. return 0;
  24948. };
  24949. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24950. /** @hidden */
  24951. get: function () {
  24952. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24953. return null;
  24954. },
  24955. enumerable: true,
  24956. configurable: true
  24957. });
  24958. /** @hidden */
  24959. Scene.prototype.getSpritesDuration = function () {
  24960. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24961. return 0;
  24962. };
  24963. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24964. /** @hidden */
  24965. get: function () {
  24966. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24967. return null;
  24968. },
  24969. enumerable: true,
  24970. configurable: true
  24971. });
  24972. /**
  24973. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24974. * @returns a number
  24975. */
  24976. Scene.prototype.getAnimationRatio = function () {
  24977. return this._animationRatio;
  24978. };
  24979. /**
  24980. * Gets an unique Id for the current frame
  24981. * @returns a number
  24982. */
  24983. Scene.prototype.getRenderId = function () {
  24984. return this._renderId;
  24985. };
  24986. /** Call this function if you want to manually increment the render Id*/
  24987. Scene.prototype.incrementRenderId = function () {
  24988. this._renderId++;
  24989. };
  24990. Scene.prototype._updatePointerPosition = function (evt) {
  24991. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24992. if (!canvasRect) {
  24993. return;
  24994. }
  24995. this._pointerX = evt.clientX - canvasRect.left;
  24996. this._pointerY = evt.clientY - canvasRect.top;
  24997. this._unTranslatedPointerX = this._pointerX;
  24998. this._unTranslatedPointerY = this._pointerY;
  24999. };
  25000. Scene.prototype._createUbo = function () {
  25001. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25002. this._sceneUbo.addUniform("viewProjection", 16);
  25003. this._sceneUbo.addUniform("view", 16);
  25004. };
  25005. Scene.prototype._createAlternateUbo = function () {
  25006. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25007. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25008. this._alternateSceneUbo.addUniform("view", 16);
  25009. };
  25010. // Pointers handling
  25011. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25012. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25013. if (result) {
  25014. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25015. }
  25016. return result;
  25017. };
  25018. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25019. if (pointerInfo.pickInfo) {
  25020. if (!pointerInfo.pickInfo.ray) {
  25021. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25022. }
  25023. }
  25024. };
  25025. /**
  25026. * Use this method to simulate a pointer move on a mesh
  25027. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25028. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25029. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25030. * @returns the current scene
  25031. */
  25032. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25033. var evt = new PointerEvent("pointermove", pointerEventInit);
  25034. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25035. return this;
  25036. }
  25037. return this._processPointerMove(pickResult, evt);
  25038. };
  25039. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25040. var canvas = this._engine.getRenderingCanvas();
  25041. if (!canvas) {
  25042. return this;
  25043. }
  25044. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25045. this.setPointerOverSprite(null);
  25046. this.setPointerOverMesh(pickResult.pickedMesh);
  25047. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25048. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25049. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25050. }
  25051. else {
  25052. canvas.style.cursor = this.hoverCursor;
  25053. }
  25054. }
  25055. else {
  25056. canvas.style.cursor = this.defaultCursor;
  25057. }
  25058. }
  25059. else {
  25060. this.setPointerOverMesh(null);
  25061. // Sprites
  25062. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25063. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25064. this.setPointerOverSprite(pickResult.pickedSprite);
  25065. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25066. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25067. }
  25068. else {
  25069. canvas.style.cursor = this.hoverCursor;
  25070. }
  25071. }
  25072. else {
  25073. this.setPointerOverSprite(null);
  25074. // Restore pointer
  25075. canvas.style.cursor = this.defaultCursor;
  25076. }
  25077. }
  25078. if (pickResult) {
  25079. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25080. if (this.onPointerMove) {
  25081. this.onPointerMove(evt, pickResult, type);
  25082. }
  25083. if (this.onPointerObservable.hasObservers()) {
  25084. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25085. this._setRayOnPointerInfo(pi);
  25086. this.onPointerObservable.notifyObservers(pi, type);
  25087. }
  25088. }
  25089. return this;
  25090. };
  25091. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25092. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25093. if (pickResult) {
  25094. pi.ray = pickResult.ray;
  25095. }
  25096. this.onPrePointerObservable.notifyObservers(pi, type);
  25097. if (pi.skipOnPointerObservable) {
  25098. return true;
  25099. }
  25100. else {
  25101. return false;
  25102. }
  25103. };
  25104. /**
  25105. * Use this method to simulate a pointer down on a mesh
  25106. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25107. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25108. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25109. * @returns the current scene
  25110. */
  25111. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25112. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25113. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25114. return this;
  25115. }
  25116. return this._processPointerDown(pickResult, evt);
  25117. };
  25118. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25119. var _this = this;
  25120. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25121. this._pickedDownMesh = pickResult.pickedMesh;
  25122. var actionManager = pickResult.pickedMesh.actionManager;
  25123. if (actionManager) {
  25124. if (actionManager.hasPickTriggers) {
  25125. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25126. switch (evt.button) {
  25127. case 0:
  25128. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25129. break;
  25130. case 1:
  25131. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25132. break;
  25133. case 2:
  25134. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25135. break;
  25136. }
  25137. }
  25138. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25139. window.setTimeout(function () {
  25140. 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);
  25141. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25142. if (_this._totalPointersPressed !== 0 &&
  25143. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25144. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25145. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25146. _this._startingPointerTime = 0;
  25147. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25148. }
  25149. }
  25150. }, Scene.LongPressDelay);
  25151. }
  25152. }
  25153. }
  25154. if (pickResult) {
  25155. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25156. if (this.onPointerDown) {
  25157. this.onPointerDown(evt, pickResult, type);
  25158. }
  25159. if (this.onPointerObservable.hasObservers()) {
  25160. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25161. this._setRayOnPointerInfo(pi);
  25162. this.onPointerObservable.notifyObservers(pi, type);
  25163. }
  25164. }
  25165. return this;
  25166. };
  25167. /**
  25168. * Use this method to simulate a pointer up on a mesh
  25169. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25170. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25171. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25172. * @returns the current scene
  25173. */
  25174. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25175. var evt = new PointerEvent("pointerup", pointerEventInit);
  25176. var clickInfo = new ClickInfo();
  25177. clickInfo.singleClick = true;
  25178. clickInfo.ignore = true;
  25179. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25180. return this;
  25181. }
  25182. return this._processPointerUp(pickResult, evt, clickInfo);
  25183. };
  25184. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25185. if (pickResult && pickResult && pickResult.pickedMesh) {
  25186. this._pickedUpMesh = pickResult.pickedMesh;
  25187. if (this._pickedDownMesh === this._pickedUpMesh) {
  25188. if (this.onPointerPick) {
  25189. this.onPointerPick(evt, pickResult);
  25190. }
  25191. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25192. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25193. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25194. this._setRayOnPointerInfo(pi);
  25195. this.onPointerObservable.notifyObservers(pi, type_1);
  25196. }
  25197. }
  25198. if (pickResult.pickedMesh.actionManager) {
  25199. if (clickInfo.ignore) {
  25200. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25201. }
  25202. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25203. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25204. }
  25205. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25206. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25207. }
  25208. }
  25209. }
  25210. if (this._pickedDownMesh &&
  25211. this._pickedDownMesh.actionManager &&
  25212. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25213. this._pickedDownMesh !== this._pickedUpMesh) {
  25214. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25215. }
  25216. var type = BABYLON.PointerEventTypes.POINTERUP;
  25217. if (this.onPointerObservable.hasObservers()) {
  25218. if (!clickInfo.ignore) {
  25219. if (!clickInfo.hasSwiped) {
  25220. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25221. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25222. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25223. this._setRayOnPointerInfo(pi);
  25224. this.onPointerObservable.notifyObservers(pi, type_2);
  25225. }
  25226. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25227. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25228. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25229. this._setRayOnPointerInfo(pi);
  25230. this.onPointerObservable.notifyObservers(pi, type_3);
  25231. }
  25232. }
  25233. }
  25234. else {
  25235. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25236. this._setRayOnPointerInfo(pi);
  25237. this.onPointerObservable.notifyObservers(pi, type);
  25238. }
  25239. }
  25240. if (this.onPointerUp) {
  25241. this.onPointerUp(evt, pickResult, type);
  25242. }
  25243. return this;
  25244. };
  25245. /**
  25246. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25247. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25248. * @returns true if the pointer was captured
  25249. */
  25250. Scene.prototype.isPointerCaptured = function (pointerId) {
  25251. if (pointerId === void 0) { pointerId = 0; }
  25252. return this._pointerCaptures[pointerId];
  25253. };
  25254. /**
  25255. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25256. * @param attachUp defines if you want to attach events to pointerup
  25257. * @param attachDown defines if you want to attach events to pointerdown
  25258. * @param attachMove defines if you want to attach events to pointermove
  25259. */
  25260. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25261. var _this = this;
  25262. if (attachUp === void 0) { attachUp = true; }
  25263. if (attachDown === void 0) { attachDown = true; }
  25264. if (attachMove === void 0) { attachMove = true; }
  25265. this._initActionManager = function (act, clickInfo) {
  25266. if (!_this._meshPickProceed) {
  25267. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25268. _this._currentPickResult = pickResult;
  25269. if (pickResult) {
  25270. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25271. }
  25272. _this._meshPickProceed = true;
  25273. }
  25274. return act;
  25275. };
  25276. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25277. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25278. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25279. btn !== _this._previousButtonPressed) {
  25280. _this._doubleClickOccured = false;
  25281. clickInfo.singleClick = true;
  25282. clickInfo.ignore = false;
  25283. cb(clickInfo, _this._currentPickResult);
  25284. }
  25285. };
  25286. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25287. var clickInfo = new ClickInfo();
  25288. _this._currentPickResult = null;
  25289. var act = null;
  25290. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25291. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25292. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25293. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25294. act = _this._initActionManager(act, clickInfo);
  25295. if (act)
  25296. checkPicking = act.hasPickTriggers;
  25297. }
  25298. if (checkPicking) {
  25299. var btn = evt.button;
  25300. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25301. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25302. if (!clickInfo.hasSwiped) {
  25303. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25304. if (!checkSingleClickImmediately) {
  25305. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25306. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25307. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25308. act = _this._initActionManager(act, clickInfo);
  25309. if (act)
  25310. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25311. }
  25312. }
  25313. if (checkSingleClickImmediately) {
  25314. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25315. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25316. btn !== _this._previousButtonPressed) {
  25317. clickInfo.singleClick = true;
  25318. cb(clickInfo, _this._currentPickResult);
  25319. }
  25320. }
  25321. // at least one double click is required to be check and exclusive double click is enabled
  25322. else {
  25323. // wait that no double click has been raised during the double click delay
  25324. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25325. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25326. }
  25327. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25328. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25329. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25330. act = _this._initActionManager(act, clickInfo);
  25331. if (act)
  25332. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25333. }
  25334. if (checkDoubleClick) {
  25335. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25336. if (btn === _this._previousButtonPressed &&
  25337. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25338. !_this._doubleClickOccured) {
  25339. // pointer has not moved for 2 clicks, it's a double click
  25340. if (!clickInfo.hasSwiped &&
  25341. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25342. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25343. _this._previousStartingPointerTime = 0;
  25344. _this._doubleClickOccured = true;
  25345. clickInfo.doubleClick = true;
  25346. clickInfo.ignore = false;
  25347. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25348. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25349. }
  25350. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25351. cb(clickInfo, _this._currentPickResult);
  25352. }
  25353. // if the two successive clicks are too far, it's just two simple clicks
  25354. else {
  25355. _this._doubleClickOccured = false;
  25356. _this._previousStartingPointerTime = _this._startingPointerTime;
  25357. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25358. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25359. _this._previousButtonPressed = btn;
  25360. if (Scene.ExclusiveDoubleClickMode) {
  25361. if (_this._previousDelayedSimpleClickTimeout) {
  25362. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25363. }
  25364. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25365. cb(clickInfo, _this._previousPickResult);
  25366. }
  25367. else {
  25368. cb(clickInfo, _this._currentPickResult);
  25369. }
  25370. }
  25371. }
  25372. // just the first click of the double has been raised
  25373. else {
  25374. _this._doubleClickOccured = false;
  25375. _this._previousStartingPointerTime = _this._startingPointerTime;
  25376. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25377. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25378. _this._previousButtonPressed = btn;
  25379. }
  25380. }
  25381. }
  25382. }
  25383. clickInfo.ignore = true;
  25384. cb(clickInfo, _this._currentPickResult);
  25385. };
  25386. this._spritePredicate = function (sprite) {
  25387. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25388. };
  25389. this._onPointerMove = function (evt) {
  25390. _this._updatePointerPosition(evt);
  25391. // PreObservable support
  25392. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25393. return;
  25394. }
  25395. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25396. return;
  25397. }
  25398. if (!_this.pointerMovePredicate) {
  25399. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25400. }
  25401. // Meshes
  25402. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25403. _this._processPointerMove(pickResult, evt);
  25404. };
  25405. this._onPointerDown = function (evt) {
  25406. _this._totalPointersPressed++;
  25407. _this._pickedDownMesh = null;
  25408. _this._meshPickProceed = false;
  25409. _this._updatePointerPosition(evt);
  25410. if (_this.preventDefaultOnPointerDown && canvas) {
  25411. evt.preventDefault();
  25412. canvas.focus();
  25413. }
  25414. // PreObservable support
  25415. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25416. return;
  25417. }
  25418. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25419. return;
  25420. }
  25421. _this._pointerCaptures[evt.pointerId] = true;
  25422. _this._startingPointerPosition.x = _this._pointerX;
  25423. _this._startingPointerPosition.y = _this._pointerY;
  25424. _this._startingPointerTime = Date.now();
  25425. if (!_this.pointerDownPredicate) {
  25426. _this.pointerDownPredicate = function (mesh) {
  25427. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25428. };
  25429. }
  25430. // Meshes
  25431. _this._pickedDownMesh = null;
  25432. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25433. _this._processPointerDown(pickResult, evt);
  25434. // Sprites
  25435. _this._pickedDownSprite = null;
  25436. if (_this.spriteManagers.length > 0) {
  25437. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25438. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25439. if (pickResult.pickedSprite.actionManager) {
  25440. _this._pickedDownSprite = pickResult.pickedSprite;
  25441. switch (evt.button) {
  25442. case 0:
  25443. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25444. break;
  25445. case 1:
  25446. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25447. break;
  25448. case 2:
  25449. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25450. break;
  25451. }
  25452. if (pickResult.pickedSprite.actionManager) {
  25453. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25454. }
  25455. }
  25456. }
  25457. }
  25458. };
  25459. this._onPointerUp = function (evt) {
  25460. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25461. return; // So we need to test it the pointer down was pressed before.
  25462. }
  25463. _this._totalPointersPressed--;
  25464. _this._pickedUpMesh = null;
  25465. _this._meshPickProceed = false;
  25466. _this._updatePointerPosition(evt);
  25467. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25468. // PreObservable support
  25469. if (_this.onPrePointerObservable.hasObservers()) {
  25470. if (!clickInfo.ignore) {
  25471. if (!clickInfo.hasSwiped) {
  25472. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25473. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25474. return;
  25475. }
  25476. }
  25477. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25478. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25479. return;
  25480. }
  25481. }
  25482. }
  25483. }
  25484. else {
  25485. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25486. return;
  25487. }
  25488. }
  25489. }
  25490. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25491. return;
  25492. }
  25493. _this._pointerCaptures[evt.pointerId] = false;
  25494. if (!_this.pointerUpPredicate) {
  25495. _this.pointerUpPredicate = function (mesh) {
  25496. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25497. };
  25498. }
  25499. // Meshes
  25500. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25501. _this._initActionManager(null, clickInfo);
  25502. }
  25503. if (!pickResult) {
  25504. pickResult = _this._currentPickResult;
  25505. }
  25506. _this._processPointerUp(pickResult, evt, clickInfo);
  25507. // Sprites
  25508. if (!clickInfo.ignore) {
  25509. if (_this.spriteManagers.length > 0) {
  25510. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25511. if (spritePickResult) {
  25512. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25513. if (spritePickResult.pickedSprite.actionManager) {
  25514. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25515. if (spritePickResult.pickedSprite.actionManager) {
  25516. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25517. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25518. }
  25519. }
  25520. }
  25521. }
  25522. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25523. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25524. }
  25525. }
  25526. }
  25527. }
  25528. _this._previousPickResult = _this._currentPickResult;
  25529. });
  25530. };
  25531. this._onKeyDown = function (evt) {
  25532. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25533. if (_this.onPreKeyboardObservable.hasObservers()) {
  25534. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25535. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25536. if (pi.skipOnPointerObservable) {
  25537. return;
  25538. }
  25539. }
  25540. if (_this.onKeyboardObservable.hasObservers()) {
  25541. var pi = new BABYLON.KeyboardInfo(type, evt);
  25542. _this.onKeyboardObservable.notifyObservers(pi, type);
  25543. }
  25544. if (_this.actionManager) {
  25545. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25546. }
  25547. };
  25548. this._onKeyUp = function (evt) {
  25549. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25550. if (_this.onPreKeyboardObservable.hasObservers()) {
  25551. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25552. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25553. if (pi.skipOnPointerObservable) {
  25554. return;
  25555. }
  25556. }
  25557. if (_this.onKeyboardObservable.hasObservers()) {
  25558. var pi = new BABYLON.KeyboardInfo(type, evt);
  25559. _this.onKeyboardObservable.notifyObservers(pi, type);
  25560. }
  25561. if (_this.actionManager) {
  25562. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25563. }
  25564. };
  25565. var engine = this.getEngine();
  25566. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25567. if (!canvas) {
  25568. return;
  25569. }
  25570. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25571. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25572. });
  25573. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25574. if (!canvas) {
  25575. return;
  25576. }
  25577. canvas.removeEventListener("keydown", _this._onKeyDown);
  25578. canvas.removeEventListener("keyup", _this._onKeyUp);
  25579. });
  25580. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25581. var canvas = this._engine.getRenderingCanvas();
  25582. if (!canvas) {
  25583. return;
  25584. }
  25585. if (attachMove) {
  25586. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25587. // Wheel
  25588. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25589. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25590. }
  25591. if (attachDown) {
  25592. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25593. }
  25594. if (attachUp) {
  25595. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25596. }
  25597. canvas.tabIndex = 1;
  25598. };
  25599. /** Detaches all event handlers*/
  25600. Scene.prototype.detachControl = function () {
  25601. var engine = this.getEngine();
  25602. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25603. var canvas = engine.getRenderingCanvas();
  25604. if (!canvas) {
  25605. return;
  25606. }
  25607. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25608. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25609. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25610. if (this._onCanvasBlurObserver) {
  25611. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25612. }
  25613. if (this._onCanvasFocusObserver) {
  25614. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25615. }
  25616. // Wheel
  25617. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25618. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25619. // Keyboard
  25620. canvas.removeEventListener("keydown", this._onKeyDown);
  25621. canvas.removeEventListener("keyup", this._onKeyUp);
  25622. // Observables
  25623. this.onKeyboardObservable.clear();
  25624. this.onPreKeyboardObservable.clear();
  25625. this.onPointerObservable.clear();
  25626. this.onPrePointerObservable.clear();
  25627. };
  25628. /**
  25629. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25630. * Delay loaded resources are not taking in account
  25631. * @return true if all required resources are ready
  25632. */
  25633. Scene.prototype.isReady = function () {
  25634. if (this._isDisposed) {
  25635. return false;
  25636. }
  25637. if (this._pendingData.length > 0) {
  25638. return false;
  25639. }
  25640. var index;
  25641. var engine = this.getEngine();
  25642. // Geometries
  25643. for (index = 0; index < this._geometries.length; index++) {
  25644. var geometry = this._geometries[index];
  25645. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25646. return false;
  25647. }
  25648. }
  25649. // Meshes
  25650. for (index = 0; index < this.meshes.length; index++) {
  25651. var mesh = this.meshes[index];
  25652. if (!mesh.isEnabled()) {
  25653. continue;
  25654. }
  25655. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25656. continue;
  25657. }
  25658. if (!mesh.isReady(true)) {
  25659. return false;
  25660. }
  25661. // Effect layers
  25662. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25663. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25664. var layer = _a[_i];
  25665. if (!layer.hasMesh(mesh)) {
  25666. continue;
  25667. }
  25668. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25669. var subMesh = _c[_b];
  25670. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25671. return false;
  25672. }
  25673. }
  25674. }
  25675. }
  25676. // Post-processes
  25677. if (this.activeCameras && this.activeCameras.length > 0) {
  25678. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25679. var camera = _e[_d];
  25680. if (!camera.isReady(true)) {
  25681. return false;
  25682. }
  25683. }
  25684. }
  25685. else if (this.activeCamera) {
  25686. if (!this.activeCamera.isReady(true)) {
  25687. return false;
  25688. }
  25689. }
  25690. // Particles
  25691. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25692. var particleSystem = _g[_f];
  25693. if (!particleSystem.isReady()) {
  25694. return false;
  25695. }
  25696. }
  25697. return true;
  25698. };
  25699. /** Resets all cached information relative to material (including effect and visibility) */
  25700. Scene.prototype.resetCachedMaterial = function () {
  25701. this._cachedMaterial = null;
  25702. this._cachedEffect = null;
  25703. this._cachedVisibility = null;
  25704. };
  25705. /**
  25706. * Registers a function to be called before every frame render
  25707. * @param func defines the function to register
  25708. */
  25709. Scene.prototype.registerBeforeRender = function (func) {
  25710. this.onBeforeRenderObservable.add(func);
  25711. };
  25712. /**
  25713. * Unregisters a function called before every frame render
  25714. * @param func defines the function to unregister
  25715. */
  25716. Scene.prototype.unregisterBeforeRender = function (func) {
  25717. this.onBeforeRenderObservable.removeCallback(func);
  25718. };
  25719. /**
  25720. * Registers a function to be called after every frame render
  25721. * @param func defines the function to register
  25722. */
  25723. Scene.prototype.registerAfterRender = function (func) {
  25724. this.onAfterRenderObservable.add(func);
  25725. };
  25726. /**
  25727. * Unregisters a function called after every frame render
  25728. * @param func defines the function to unregister
  25729. */
  25730. Scene.prototype.unregisterAfterRender = function (func) {
  25731. this.onAfterRenderObservable.removeCallback(func);
  25732. };
  25733. Scene.prototype._executeOnceBeforeRender = function (func) {
  25734. var _this = this;
  25735. var execFunc = function () {
  25736. func();
  25737. setTimeout(function () {
  25738. _this.unregisterBeforeRender(execFunc);
  25739. });
  25740. };
  25741. this.registerBeforeRender(execFunc);
  25742. };
  25743. /**
  25744. * The provided function will run before render once and will be disposed afterwards.
  25745. * A timeout delay can be provided so that the function will be executed in N ms.
  25746. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25747. * @param func The function to be executed.
  25748. * @param timeout optional delay in ms
  25749. */
  25750. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25751. var _this = this;
  25752. if (timeout !== undefined) {
  25753. setTimeout(function () {
  25754. _this._executeOnceBeforeRender(func);
  25755. }, timeout);
  25756. }
  25757. else {
  25758. this._executeOnceBeforeRender(func);
  25759. }
  25760. };
  25761. /** @hidden */
  25762. Scene.prototype._addPendingData = function (data) {
  25763. this._pendingData.push(data);
  25764. };
  25765. /** @hidden */
  25766. Scene.prototype._removePendingData = function (data) {
  25767. var wasLoading = this.isLoading;
  25768. var index = this._pendingData.indexOf(data);
  25769. if (index !== -1) {
  25770. this._pendingData.splice(index, 1);
  25771. }
  25772. if (wasLoading && !this.isLoading) {
  25773. this.onDataLoadedObservable.notifyObservers(this);
  25774. }
  25775. };
  25776. /**
  25777. * Returns the number of items waiting to be loaded
  25778. * @returns the number of items waiting to be loaded
  25779. */
  25780. Scene.prototype.getWaitingItemsCount = function () {
  25781. return this._pendingData.length;
  25782. };
  25783. Object.defineProperty(Scene.prototype, "isLoading", {
  25784. /**
  25785. * Returns a boolean indicating if the scene is still loading data
  25786. */
  25787. get: function () {
  25788. return this._pendingData.length > 0;
  25789. },
  25790. enumerable: true,
  25791. configurable: true
  25792. });
  25793. /**
  25794. * Registers a function to be executed when the scene is ready
  25795. * @param {Function} func - the function to be executed
  25796. */
  25797. Scene.prototype.executeWhenReady = function (func) {
  25798. var _this = this;
  25799. this.onReadyObservable.add(func);
  25800. if (this._executeWhenReadyTimeoutId !== -1) {
  25801. return;
  25802. }
  25803. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25804. _this._checkIsReady();
  25805. }, 150);
  25806. };
  25807. /**
  25808. * Returns a promise that resolves when the scene is ready
  25809. * @returns A promise that resolves when the scene is ready
  25810. */
  25811. Scene.prototype.whenReadyAsync = function () {
  25812. var _this = this;
  25813. return new Promise(function (resolve) {
  25814. _this.executeWhenReady(function () {
  25815. resolve();
  25816. });
  25817. });
  25818. };
  25819. /** @hidden */
  25820. Scene.prototype._checkIsReady = function () {
  25821. var _this = this;
  25822. if (this.isReady()) {
  25823. this.onReadyObservable.notifyObservers(this);
  25824. this.onReadyObservable.clear();
  25825. this._executeWhenReadyTimeoutId = -1;
  25826. return;
  25827. }
  25828. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25829. _this._checkIsReady();
  25830. }, 150);
  25831. };
  25832. // Animations
  25833. /**
  25834. * Will start the animation sequence of a given target
  25835. * @param target defines the target
  25836. * @param from defines from which frame should animation start
  25837. * @param to defines until which frame should animation run.
  25838. * @param weight defines the weight to apply to the animation (1.0 by default)
  25839. * @param loop defines if the animation loops
  25840. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25841. * @param onAnimationEnd defines the function to be executed when the animation ends
  25842. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25843. * @returns the animatable object created for this animation
  25844. */
  25845. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25846. if (weight === void 0) { weight = 1.0; }
  25847. if (speedRatio === void 0) { speedRatio = 1.0; }
  25848. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25849. returnedAnimatable.weight = weight;
  25850. return returnedAnimatable;
  25851. };
  25852. /**
  25853. * Will start the animation sequence of a given target
  25854. * @param target defines the target
  25855. * @param from defines from which frame should animation start
  25856. * @param to defines until which frame should animation run.
  25857. * @param loop defines if the animation loops
  25858. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25859. * @param onAnimationEnd defines the function to be executed when the animation ends
  25860. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25861. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25862. * @returns the animatable object created for this animation
  25863. */
  25864. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25865. if (speedRatio === void 0) { speedRatio = 1.0; }
  25866. if (stopCurrent === void 0) { stopCurrent = true; }
  25867. if (from > to && speedRatio > 0) {
  25868. speedRatio *= -1;
  25869. }
  25870. if (stopCurrent) {
  25871. this.stopAnimation(target);
  25872. }
  25873. if (!animatable) {
  25874. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25875. }
  25876. // Local animations
  25877. if (target.animations) {
  25878. animatable.appendAnimations(target, target.animations);
  25879. }
  25880. // Children animations
  25881. if (target.getAnimatables) {
  25882. var animatables = target.getAnimatables();
  25883. for (var index = 0; index < animatables.length; index++) {
  25884. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25885. }
  25886. }
  25887. animatable.reset();
  25888. return animatable;
  25889. };
  25890. /**
  25891. * Begin a new animation on a given node
  25892. * @param target defines the target where the animation will take place
  25893. * @param animations defines the list of animations to start
  25894. * @param from defines the initial value
  25895. * @param to defines the final value
  25896. * @param loop defines if you want animation to loop (off by default)
  25897. * @param speedRatio defines the speed ratio to apply to all animations
  25898. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25899. * @returns the list of created animatables
  25900. */
  25901. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25902. if (speedRatio === undefined) {
  25903. speedRatio = 1.0;
  25904. }
  25905. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25906. return animatable;
  25907. };
  25908. /**
  25909. * Begin a new animation on a given node and its hierarchy
  25910. * @param target defines the root node where the animation will take place
  25911. * @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.
  25912. * @param animations defines the list of animations to start
  25913. * @param from defines the initial value
  25914. * @param to defines the final value
  25915. * @param loop defines if you want animation to loop (off by default)
  25916. * @param speedRatio defines the speed ratio to apply to all animations
  25917. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25918. * @returns the list of animatables created for all nodes
  25919. */
  25920. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25921. var children = target.getDescendants(directDescendantsOnly);
  25922. var result = [];
  25923. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25924. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25925. var child = children_1[_i];
  25926. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25927. }
  25928. return result;
  25929. };
  25930. /**
  25931. * Gets the animatable associated with a specific target
  25932. * @param target defines the target of the animatable
  25933. * @returns the required animatable if found
  25934. */
  25935. Scene.prototype.getAnimatableByTarget = function (target) {
  25936. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25937. if (this._activeAnimatables[index].target === target) {
  25938. return this._activeAnimatables[index];
  25939. }
  25940. }
  25941. return null;
  25942. };
  25943. /**
  25944. * Gets all animatables associated with a given target
  25945. * @param target defines the target to look animatables for
  25946. * @returns an array of Animatables
  25947. */
  25948. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25949. var result = [];
  25950. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25951. if (this._activeAnimatables[index].target === target) {
  25952. result.push(this._activeAnimatables[index]);
  25953. }
  25954. }
  25955. return result;
  25956. };
  25957. Object.defineProperty(Scene.prototype, "animatables", {
  25958. /**
  25959. * Gets all animatable attached to the scene
  25960. */
  25961. get: function () {
  25962. return this._activeAnimatables;
  25963. },
  25964. enumerable: true,
  25965. configurable: true
  25966. });
  25967. /**
  25968. * Will stop the animation of the given target
  25969. * @param target - the target
  25970. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25971. */
  25972. Scene.prototype.stopAnimation = function (target, animationName) {
  25973. var animatables = this.getAllAnimatablesByTarget(target);
  25974. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25975. var animatable = animatables_1[_i];
  25976. animatable.stop(animationName);
  25977. }
  25978. };
  25979. /**
  25980. * Stops and removes all animations that have been applied to the scene
  25981. */
  25982. Scene.prototype.stopAllAnimations = function () {
  25983. if (this._activeAnimatables) {
  25984. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25985. this._activeAnimatables[i].stop();
  25986. }
  25987. this._activeAnimatables = [];
  25988. }
  25989. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25990. var group = _a[_i];
  25991. group.stop();
  25992. }
  25993. };
  25994. Scene.prototype._animate = function () {
  25995. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25996. return;
  25997. }
  25998. // Getting time
  25999. var now = BABYLON.Tools.Now;
  26000. if (!this._animationTimeLast) {
  26001. if (this._pendingData.length > 0) {
  26002. return;
  26003. }
  26004. this._animationTimeLast = now;
  26005. }
  26006. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26007. this._animationTime += deltaTime;
  26008. this._animationTimeLast = now;
  26009. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26010. this._activeAnimatables[index]._animate(this._animationTime);
  26011. }
  26012. // Late animation bindings
  26013. this._processLateAnimationBindings();
  26014. };
  26015. /** @hidden */
  26016. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26017. var target = runtimeAnimation.target;
  26018. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26019. if (!target._lateAnimationHolders) {
  26020. target._lateAnimationHolders = {};
  26021. }
  26022. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26023. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26024. totalWeight: 0,
  26025. animations: [],
  26026. originalValue: originalValue
  26027. };
  26028. }
  26029. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26030. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26031. };
  26032. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26033. var normalizer = 1.0;
  26034. var finalPosition = BABYLON.Tmp.Vector3[0];
  26035. var finalScaling = BABYLON.Tmp.Vector3[1];
  26036. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26037. var startIndex = 0;
  26038. var originalAnimation = holder.animations[0];
  26039. var originalValue = holder.originalValue;
  26040. var scale = 1;
  26041. if (holder.totalWeight < 1.0) {
  26042. // We need to mix the original value in
  26043. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26044. scale = 1.0 - holder.totalWeight;
  26045. }
  26046. else {
  26047. startIndex = 1;
  26048. // We need to normalize the weights
  26049. normalizer = holder.totalWeight;
  26050. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26051. scale = originalAnimation.weight / normalizer;
  26052. if (scale == 1) {
  26053. return originalAnimation.currentValue;
  26054. }
  26055. }
  26056. finalScaling.scaleInPlace(scale);
  26057. finalPosition.scaleInPlace(scale);
  26058. finalQuaternion.scaleInPlace(scale);
  26059. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26060. var runtimeAnimation = holder.animations[animIndex];
  26061. var scale = runtimeAnimation.weight / normalizer;
  26062. var currentPosition = BABYLON.Tmp.Vector3[2];
  26063. var currentScaling = BABYLON.Tmp.Vector3[3];
  26064. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26065. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26066. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26067. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26068. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26069. }
  26070. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26071. return originalAnimation._workValue;
  26072. };
  26073. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26074. var originalAnimation = holder.animations[0];
  26075. var originalValue = holder.originalValue;
  26076. if (holder.animations.length === 1) {
  26077. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26078. }
  26079. var normalizer = 1.0;
  26080. var quaternions;
  26081. var weights;
  26082. if (holder.totalWeight < 1.0) {
  26083. var scale = 1.0 - holder.totalWeight;
  26084. quaternions = [];
  26085. weights = [];
  26086. quaternions.push(originalValue);
  26087. weights.push(scale);
  26088. }
  26089. else {
  26090. if (holder.animations.length === 2) { // Slerp as soon as we can
  26091. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26092. }
  26093. quaternions = [];
  26094. weights = [];
  26095. normalizer = holder.totalWeight;
  26096. }
  26097. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26098. var runtimeAnimation = holder.animations[animIndex];
  26099. quaternions.push(runtimeAnimation.currentValue);
  26100. weights.push(runtimeAnimation.weight / normalizer);
  26101. }
  26102. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26103. var cumulativeAmount = 0;
  26104. var cumulativeQuaternion = null;
  26105. for (var index = 0; index < quaternions.length;) {
  26106. if (!cumulativeQuaternion) {
  26107. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26108. cumulativeAmount = weights[index] + weights[index + 1];
  26109. index += 2;
  26110. continue;
  26111. }
  26112. cumulativeAmount += weights[index];
  26113. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26114. index++;
  26115. }
  26116. return cumulativeQuaternion;
  26117. };
  26118. Scene.prototype._processLateAnimationBindings = function () {
  26119. if (!this._registeredForLateAnimationBindings.length) {
  26120. return;
  26121. }
  26122. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26123. var target = this._registeredForLateAnimationBindings.data[index];
  26124. for (var path in target._lateAnimationHolders) {
  26125. var holder = target._lateAnimationHolders[path];
  26126. var originalAnimation = holder.animations[0];
  26127. var originalValue = holder.originalValue;
  26128. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26129. var finalValue = void 0;
  26130. if (matrixDecomposeMode) {
  26131. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26132. }
  26133. else {
  26134. var quaternionMode = originalValue.w !== undefined;
  26135. if (quaternionMode) {
  26136. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26137. }
  26138. else {
  26139. var startIndex = 0;
  26140. var normalizer = 1.0;
  26141. if (holder.totalWeight < 1.0) {
  26142. // We need to mix the original value in
  26143. if (originalValue.scale) {
  26144. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26145. }
  26146. else {
  26147. finalValue = originalValue * (1.0 - holder.totalWeight);
  26148. }
  26149. }
  26150. else {
  26151. // We need to normalize the weights
  26152. normalizer = holder.totalWeight;
  26153. var scale_1 = originalAnimation.weight / normalizer;
  26154. if (scale_1 !== 1) {
  26155. if (originalAnimation.currentValue.scale) {
  26156. finalValue = originalAnimation.currentValue.scale(scale_1);
  26157. }
  26158. else {
  26159. finalValue = originalAnimation.currentValue * scale_1;
  26160. }
  26161. }
  26162. else {
  26163. finalValue = originalAnimation.currentValue;
  26164. }
  26165. startIndex = 1;
  26166. }
  26167. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26168. var runtimeAnimation = holder.animations[animIndex];
  26169. var scale = runtimeAnimation.weight / normalizer;
  26170. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26171. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26172. }
  26173. else {
  26174. finalValue += runtimeAnimation.currentValue * scale;
  26175. }
  26176. }
  26177. }
  26178. }
  26179. target[path] = finalValue;
  26180. }
  26181. target._lateAnimationHolders = {};
  26182. }
  26183. this._registeredForLateAnimationBindings.reset();
  26184. };
  26185. // Matrix
  26186. /** @hidden */
  26187. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26188. this._useAlternateCameraConfiguration = active;
  26189. };
  26190. /**
  26191. * Gets the current view matrix
  26192. * @returns a Matrix
  26193. */
  26194. Scene.prototype.getViewMatrix = function () {
  26195. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26196. };
  26197. /**
  26198. * Gets the current projection matrix
  26199. * @returns a Matrix
  26200. */
  26201. Scene.prototype.getProjectionMatrix = function () {
  26202. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26203. };
  26204. /**
  26205. * Gets the current transform matrix
  26206. * @returns a Matrix made of View * Projection
  26207. */
  26208. Scene.prototype.getTransformMatrix = function () {
  26209. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26210. };
  26211. /**
  26212. * Sets the current transform matrix
  26213. * @param view defines the View matrix to use
  26214. * @param projection defines the Projection matrix to use
  26215. */
  26216. Scene.prototype.setTransformMatrix = function (view, projection) {
  26217. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26218. return;
  26219. }
  26220. this._viewUpdateFlag = view.updateFlag;
  26221. this._projectionUpdateFlag = projection.updateFlag;
  26222. this._viewMatrix = view;
  26223. this._projectionMatrix = projection;
  26224. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26225. // Update frustum
  26226. if (!this._frustumPlanes) {
  26227. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26228. }
  26229. else {
  26230. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26231. }
  26232. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26233. var otherCamera = this.activeCamera._alternateCamera;
  26234. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26235. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26236. }
  26237. if (this._sceneUbo.useUbo) {
  26238. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26239. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26240. this._sceneUbo.update();
  26241. }
  26242. };
  26243. /** @hidden */
  26244. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26245. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26246. return;
  26247. }
  26248. this._alternateViewUpdateFlag = view.updateFlag;
  26249. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26250. this._alternateViewMatrix = view;
  26251. this._alternateProjectionMatrix = projection;
  26252. if (!this._alternateTransformMatrix) {
  26253. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26254. }
  26255. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26256. if (!this._alternateSceneUbo) {
  26257. this._createAlternateUbo();
  26258. }
  26259. if (this._alternateSceneUbo.useUbo) {
  26260. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26261. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26262. this._alternateSceneUbo.update();
  26263. }
  26264. };
  26265. /**
  26266. * Gets the uniform buffer used to store scene data
  26267. * @returns a UniformBuffer
  26268. */
  26269. Scene.prototype.getSceneUniformBuffer = function () {
  26270. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26271. };
  26272. /**
  26273. * Gets an unique (relatively to the current scene) Id
  26274. * @returns an unique number for the scene
  26275. */
  26276. Scene.prototype.getUniqueId = function () {
  26277. var result = Scene._uniqueIdCounter;
  26278. Scene._uniqueIdCounter++;
  26279. return result;
  26280. };
  26281. /**
  26282. * Add a mesh to the list of scene's meshes
  26283. * @param newMesh defines the mesh to add
  26284. * @param recursive if all child meshes should also be added to the scene
  26285. */
  26286. Scene.prototype.addMesh = function (newMesh, recursive) {
  26287. var _this = this;
  26288. if (recursive === void 0) { recursive = false; }
  26289. this.meshes.push(newMesh);
  26290. //notify the collision coordinator
  26291. if (this.collisionCoordinator) {
  26292. this.collisionCoordinator.onMeshAdded(newMesh);
  26293. }
  26294. newMesh._resyncLightSources();
  26295. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26296. if (recursive) {
  26297. newMesh.getChildMeshes().forEach(function (m) {
  26298. _this.addMesh(m);
  26299. });
  26300. }
  26301. };
  26302. /**
  26303. * Remove a mesh for the list of scene's meshes
  26304. * @param toRemove defines the mesh to remove
  26305. * @param recursive if all child meshes should also be removed from the scene
  26306. * @returns the index where the mesh was in the mesh list
  26307. */
  26308. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26309. var _this = this;
  26310. if (recursive === void 0) { recursive = false; }
  26311. var index = this.meshes.indexOf(toRemove);
  26312. if (index !== -1) {
  26313. // Remove from the scene if mesh found
  26314. this.meshes.splice(index, 1);
  26315. }
  26316. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26317. if (recursive) {
  26318. toRemove.getChildMeshes().forEach(function (m) {
  26319. _this.removeMesh(m);
  26320. });
  26321. }
  26322. return index;
  26323. };
  26324. /**
  26325. * Add a transform node to the list of scene's transform nodes
  26326. * @param newTransformNode defines the transform node to add
  26327. */
  26328. Scene.prototype.addTransformNode = function (newTransformNode) {
  26329. this.transformNodes.push(newTransformNode);
  26330. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26331. };
  26332. /**
  26333. * Remove a transform node for the list of scene's transform nodes
  26334. * @param toRemove defines the transform node to remove
  26335. * @returns the index where the transform node was in the transform node list
  26336. */
  26337. Scene.prototype.removeTransformNode = function (toRemove) {
  26338. var index = this.transformNodes.indexOf(toRemove);
  26339. if (index !== -1) {
  26340. // Remove from the scene if found
  26341. this.transformNodes.splice(index, 1);
  26342. }
  26343. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26344. return index;
  26345. };
  26346. /**
  26347. * Remove a skeleton for the list of scene's skeletons
  26348. * @param toRemove defines the skeleton to remove
  26349. * @returns the index where the skeleton was in the skeleton list
  26350. */
  26351. Scene.prototype.removeSkeleton = function (toRemove) {
  26352. var index = this.skeletons.indexOf(toRemove);
  26353. if (index !== -1) {
  26354. // Remove from the scene if found
  26355. this.skeletons.splice(index, 1);
  26356. }
  26357. return index;
  26358. };
  26359. /**
  26360. * Remove a morph target for the list of scene's morph targets
  26361. * @param toRemove defines the morph target to remove
  26362. * @returns the index where the morph target was in the morph target list
  26363. */
  26364. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26365. var index = this.morphTargetManagers.indexOf(toRemove);
  26366. if (index !== -1) {
  26367. // Remove from the scene if found
  26368. this.morphTargetManagers.splice(index, 1);
  26369. }
  26370. return index;
  26371. };
  26372. /**
  26373. * Remove a light for the list of scene's lights
  26374. * @param toRemove defines the light to remove
  26375. * @returns the index where the light was in the light list
  26376. */
  26377. Scene.prototype.removeLight = function (toRemove) {
  26378. var index = this.lights.indexOf(toRemove);
  26379. if (index !== -1) {
  26380. // Remove from meshes
  26381. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26382. var mesh = _a[_i];
  26383. mesh._removeLightSource(toRemove);
  26384. }
  26385. // Remove from the scene if mesh found
  26386. this.lights.splice(index, 1);
  26387. this.sortLightsByPriority();
  26388. }
  26389. this.onLightRemovedObservable.notifyObservers(toRemove);
  26390. return index;
  26391. };
  26392. /**
  26393. * Remove a camera for the list of scene's cameras
  26394. * @param toRemove defines the camera to remove
  26395. * @returns the index where the camera was in the camera list
  26396. */
  26397. Scene.prototype.removeCamera = function (toRemove) {
  26398. var index = this.cameras.indexOf(toRemove);
  26399. if (index !== -1) {
  26400. // Remove from the scene if mesh found
  26401. this.cameras.splice(index, 1);
  26402. }
  26403. // Remove from activeCameras
  26404. var index2 = this.activeCameras.indexOf(toRemove);
  26405. if (index2 !== -1) {
  26406. // Remove from the scene if mesh found
  26407. this.activeCameras.splice(index2, 1);
  26408. }
  26409. // Reset the activeCamera
  26410. if (this.activeCamera === toRemove) {
  26411. if (this.cameras.length > 0) {
  26412. this.activeCamera = this.cameras[0];
  26413. }
  26414. else {
  26415. this.activeCamera = null;
  26416. }
  26417. }
  26418. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26419. return index;
  26420. };
  26421. /**
  26422. * Remove a particle system for the list of scene's particle systems
  26423. * @param toRemove defines the particle system to remove
  26424. * @returns the index where the particle system was in the particle system list
  26425. */
  26426. Scene.prototype.removeParticleSystem = function (toRemove) {
  26427. var index = this.particleSystems.indexOf(toRemove);
  26428. if (index !== -1) {
  26429. this.particleSystems.splice(index, 1);
  26430. }
  26431. return index;
  26432. };
  26433. /**
  26434. * Remove a animation for the list of scene's animations
  26435. * @param toRemove defines the animation to remove
  26436. * @returns the index where the animation was in the animation list
  26437. */
  26438. Scene.prototype.removeAnimation = function (toRemove) {
  26439. var index = this.animations.indexOf(toRemove);
  26440. if (index !== -1) {
  26441. this.animations.splice(index, 1);
  26442. }
  26443. return index;
  26444. };
  26445. /**
  26446. * Removes the given animation group from this scene.
  26447. * @param toRemove The animation group to remove
  26448. * @returns The index of the removed animation group
  26449. */
  26450. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26451. var index = this.animationGroups.indexOf(toRemove);
  26452. if (index !== -1) {
  26453. this.animationGroups.splice(index, 1);
  26454. }
  26455. return index;
  26456. };
  26457. /**
  26458. * Removes the given multi-material from this scene.
  26459. * @param toRemove The multi-material to remove
  26460. * @returns The index of the removed multi-material
  26461. */
  26462. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26463. var index = this.multiMaterials.indexOf(toRemove);
  26464. if (index !== -1) {
  26465. this.multiMaterials.splice(index, 1);
  26466. }
  26467. return index;
  26468. };
  26469. /**
  26470. * Removes the given material from this scene.
  26471. * @param toRemove The material to remove
  26472. * @returns The index of the removed material
  26473. */
  26474. Scene.prototype.removeMaterial = function (toRemove) {
  26475. var index = this.materials.indexOf(toRemove);
  26476. if (index !== -1) {
  26477. this.materials.splice(index, 1);
  26478. }
  26479. return index;
  26480. };
  26481. /**
  26482. * Removes the given lens flare system from this scene.
  26483. * @param toRemove The lens flare system to remove
  26484. * @returns The index of the removed lens flare system
  26485. */
  26486. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26487. var index = this.lensFlareSystems.indexOf(toRemove);
  26488. if (index !== -1) {
  26489. this.lensFlareSystems.splice(index, 1);
  26490. }
  26491. return index;
  26492. };
  26493. /**
  26494. * Removes the given action manager from this scene.
  26495. * @param toRemove The action manager to remove
  26496. * @returns The index of the removed action manager
  26497. */
  26498. Scene.prototype.removeActionManager = function (toRemove) {
  26499. var index = this._actionManagers.indexOf(toRemove);
  26500. if (index !== -1) {
  26501. this._actionManagers.splice(index, 1);
  26502. }
  26503. return index;
  26504. };
  26505. /**
  26506. * Removes the given effect layer from this scene.
  26507. * @param toRemove defines the effect layer to remove
  26508. * @returns the index of the removed effect layer
  26509. */
  26510. Scene.prototype.removeEffectLayer = function (toRemove) {
  26511. var index = this.effectLayers.indexOf(toRemove);
  26512. if (index !== -1) {
  26513. this.effectLayers.splice(index, 1);
  26514. }
  26515. return index;
  26516. };
  26517. /**
  26518. * Removes the given texture from this scene.
  26519. * @param toRemove The texture to remove
  26520. * @returns The index of the removed texture
  26521. */
  26522. Scene.prototype.removeTexture = function (toRemove) {
  26523. var index = this.textures.indexOf(toRemove);
  26524. if (index !== -1) {
  26525. this.textures.splice(index, 1);
  26526. }
  26527. return index;
  26528. };
  26529. /**
  26530. * Adds the given light to this scene
  26531. * @param newLight The light to add
  26532. */
  26533. Scene.prototype.addLight = function (newLight) {
  26534. this.lights.push(newLight);
  26535. this.sortLightsByPriority();
  26536. // Add light to all meshes (To support if the light is removed and then readded)
  26537. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26538. var mesh = _a[_i];
  26539. if (mesh._lightSources.indexOf(newLight) === -1) {
  26540. mesh._lightSources.push(newLight);
  26541. mesh._resyncLightSources();
  26542. }
  26543. }
  26544. this.onNewLightAddedObservable.notifyObservers(newLight);
  26545. };
  26546. /**
  26547. * Sorts the list list based on light priorities
  26548. */
  26549. Scene.prototype.sortLightsByPriority = function () {
  26550. if (this.requireLightSorting) {
  26551. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26552. }
  26553. };
  26554. /**
  26555. * Adds the given camera to this scene
  26556. * @param newCamera The camera to add
  26557. */
  26558. Scene.prototype.addCamera = function (newCamera) {
  26559. this.cameras.push(newCamera);
  26560. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26561. };
  26562. /**
  26563. * Adds the given skeleton to this scene
  26564. * @param newSkeleton The skeleton to add
  26565. */
  26566. Scene.prototype.addSkeleton = function (newSkeleton) {
  26567. this.skeletons.push(newSkeleton);
  26568. };
  26569. /**
  26570. * Adds the given particle system to this scene
  26571. * @param newParticleSystem The particle system to add
  26572. */
  26573. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26574. this.particleSystems.push(newParticleSystem);
  26575. };
  26576. /**
  26577. * Adds the given animation to this scene
  26578. * @param newAnimation The animation to add
  26579. */
  26580. Scene.prototype.addAnimation = function (newAnimation) {
  26581. this.animations.push(newAnimation);
  26582. };
  26583. /**
  26584. * Adds the given animation group to this scene.
  26585. * @param newAnimationGroup The animation group to add
  26586. */
  26587. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26588. this.animationGroups.push(newAnimationGroup);
  26589. };
  26590. /**
  26591. * Adds the given multi-material to this scene
  26592. * @param newMultiMaterial The multi-material to add
  26593. */
  26594. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26595. this.multiMaterials.push(newMultiMaterial);
  26596. };
  26597. /**
  26598. * Adds the given material to this scene
  26599. * @param newMaterial The material to add
  26600. */
  26601. Scene.prototype.addMaterial = function (newMaterial) {
  26602. this.materials.push(newMaterial);
  26603. };
  26604. /**
  26605. * Adds the given morph target to this scene
  26606. * @param newMorphTargetManager The morph target to add
  26607. */
  26608. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26609. this.morphTargetManagers.push(newMorphTargetManager);
  26610. };
  26611. /**
  26612. * Adds the given geometry to this scene
  26613. * @param newGeometry The geometry to add
  26614. */
  26615. Scene.prototype.addGeometry = function (newGeometry) {
  26616. this._geometries.push(newGeometry);
  26617. };
  26618. /**
  26619. * Adds the given lens flare system to this scene
  26620. * @param newLensFlareSystem The lens flare system to add
  26621. */
  26622. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26623. this.lensFlareSystems.push(newLensFlareSystem);
  26624. };
  26625. /**
  26626. * Adds the given effect layer to this scene
  26627. * @param newEffectLayer defines the effect layer to add
  26628. */
  26629. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26630. this.effectLayers.push(newEffectLayer);
  26631. };
  26632. /**
  26633. * Adds the given action manager to this scene
  26634. * @param newActionManager The action manager to add
  26635. */
  26636. Scene.prototype.addActionManager = function (newActionManager) {
  26637. this._actionManagers.push(newActionManager);
  26638. };
  26639. /**
  26640. * Adds the given texture to this scene.
  26641. * @param newTexture The texture to add
  26642. */
  26643. Scene.prototype.addTexture = function (newTexture) {
  26644. this.textures.push(newTexture);
  26645. };
  26646. /**
  26647. * Switch active camera
  26648. * @param newCamera defines the new active camera
  26649. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26650. */
  26651. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26652. if (attachControl === void 0) { attachControl = true; }
  26653. var canvas = this._engine.getRenderingCanvas();
  26654. if (!canvas) {
  26655. return;
  26656. }
  26657. if (this.activeCamera) {
  26658. this.activeCamera.detachControl(canvas);
  26659. }
  26660. this.activeCamera = newCamera;
  26661. if (attachControl) {
  26662. newCamera.attachControl(canvas);
  26663. }
  26664. };
  26665. /**
  26666. * sets the active camera of the scene using its ID
  26667. * @param id defines the camera's ID
  26668. * @return the new active camera or null if none found.
  26669. */
  26670. Scene.prototype.setActiveCameraByID = function (id) {
  26671. var camera = this.getCameraByID(id);
  26672. if (camera) {
  26673. this.activeCamera = camera;
  26674. return camera;
  26675. }
  26676. return null;
  26677. };
  26678. /**
  26679. * sets the active camera of the scene using its name
  26680. * @param name defines the camera's name
  26681. * @returns the new active camera or null if none found.
  26682. */
  26683. Scene.prototype.setActiveCameraByName = function (name) {
  26684. var camera = this.getCameraByName(name);
  26685. if (camera) {
  26686. this.activeCamera = camera;
  26687. return camera;
  26688. }
  26689. return null;
  26690. };
  26691. /**
  26692. * get an animation group using its name
  26693. * @param name defines the material's name
  26694. * @return the animation group or null if none found.
  26695. */
  26696. Scene.prototype.getAnimationGroupByName = function (name) {
  26697. for (var index = 0; index < this.animationGroups.length; index++) {
  26698. if (this.animationGroups[index].name === name) {
  26699. return this.animationGroups[index];
  26700. }
  26701. }
  26702. return null;
  26703. };
  26704. /**
  26705. * get a material using its id
  26706. * @param id defines the material's ID
  26707. * @return the material or null if none found.
  26708. */
  26709. Scene.prototype.getMaterialByID = function (id) {
  26710. for (var index = 0; index < this.materials.length; index++) {
  26711. if (this.materials[index].id === id) {
  26712. return this.materials[index];
  26713. }
  26714. }
  26715. return null;
  26716. };
  26717. /**
  26718. * Gets a material using its name
  26719. * @param name defines the material's name
  26720. * @return the material or null if none found.
  26721. */
  26722. Scene.prototype.getMaterialByName = function (name) {
  26723. for (var index = 0; index < this.materials.length; index++) {
  26724. if (this.materials[index].name === name) {
  26725. return this.materials[index];
  26726. }
  26727. }
  26728. return null;
  26729. };
  26730. /**
  26731. * Gets a lens flare system using its name
  26732. * @param name defines the name to look for
  26733. * @returns the lens flare system or null if not found
  26734. */
  26735. Scene.prototype.getLensFlareSystemByName = function (name) {
  26736. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26737. if (this.lensFlareSystems[index].name === name) {
  26738. return this.lensFlareSystems[index];
  26739. }
  26740. }
  26741. return null;
  26742. };
  26743. /**
  26744. * Gets a lens flare system using its id
  26745. * @param id defines the id to look for
  26746. * @returns the lens flare system or null if not found
  26747. */
  26748. Scene.prototype.getLensFlareSystemByID = function (id) {
  26749. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26750. if (this.lensFlareSystems[index].id === id) {
  26751. return this.lensFlareSystems[index];
  26752. }
  26753. }
  26754. return null;
  26755. };
  26756. /**
  26757. * Gets a camera using its id
  26758. * @param id defines the id to look for
  26759. * @returns the camera or null if not found
  26760. */
  26761. Scene.prototype.getCameraByID = function (id) {
  26762. for (var index = 0; index < this.cameras.length; index++) {
  26763. if (this.cameras[index].id === id) {
  26764. return this.cameras[index];
  26765. }
  26766. }
  26767. return null;
  26768. };
  26769. /**
  26770. * Gets a camera using its unique id
  26771. * @param uniqueId defines the unique id to look for
  26772. * @returns the camera or null if not found
  26773. */
  26774. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26775. for (var index = 0; index < this.cameras.length; index++) {
  26776. if (this.cameras[index].uniqueId === uniqueId) {
  26777. return this.cameras[index];
  26778. }
  26779. }
  26780. return null;
  26781. };
  26782. /**
  26783. * Gets a camera using its name
  26784. * @param name defines the camera's name
  26785. * @return the camera or null if none found.
  26786. */
  26787. Scene.prototype.getCameraByName = function (name) {
  26788. for (var index = 0; index < this.cameras.length; index++) {
  26789. if (this.cameras[index].name === name) {
  26790. return this.cameras[index];
  26791. }
  26792. }
  26793. return null;
  26794. };
  26795. /**
  26796. * Gets a bone using its id
  26797. * @param id defines the bone's id
  26798. * @return the bone or null if not found
  26799. */
  26800. Scene.prototype.getBoneByID = function (id) {
  26801. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26802. var skeleton = this.skeletons[skeletonIndex];
  26803. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26804. if (skeleton.bones[boneIndex].id === id) {
  26805. return skeleton.bones[boneIndex];
  26806. }
  26807. }
  26808. }
  26809. return null;
  26810. };
  26811. /**
  26812. * Gets a bone using its id
  26813. * @param name defines the bone's name
  26814. * @return the bone or null if not found
  26815. */
  26816. Scene.prototype.getBoneByName = function (name) {
  26817. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26818. var skeleton = this.skeletons[skeletonIndex];
  26819. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26820. if (skeleton.bones[boneIndex].name === name) {
  26821. return skeleton.bones[boneIndex];
  26822. }
  26823. }
  26824. }
  26825. return null;
  26826. };
  26827. /**
  26828. * Gets a light node using its name
  26829. * @param name defines the the light's name
  26830. * @return the light or null if none found.
  26831. */
  26832. Scene.prototype.getLightByName = function (name) {
  26833. for (var index = 0; index < this.lights.length; index++) {
  26834. if (this.lights[index].name === name) {
  26835. return this.lights[index];
  26836. }
  26837. }
  26838. return null;
  26839. };
  26840. /**
  26841. * Gets a light node using its id
  26842. * @param id defines the light's id
  26843. * @return the light or null if none found.
  26844. */
  26845. Scene.prototype.getLightByID = function (id) {
  26846. for (var index = 0; index < this.lights.length; index++) {
  26847. if (this.lights[index].id === id) {
  26848. return this.lights[index];
  26849. }
  26850. }
  26851. return null;
  26852. };
  26853. /**
  26854. * Gets a light node using its scene-generated unique ID
  26855. * @param uniqueId defines the light's unique id
  26856. * @return the light or null if none found.
  26857. */
  26858. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26859. for (var index = 0; index < this.lights.length; index++) {
  26860. if (this.lights[index].uniqueId === uniqueId) {
  26861. return this.lights[index];
  26862. }
  26863. }
  26864. return null;
  26865. };
  26866. /**
  26867. * Gets a particle system by id
  26868. * @param id defines the particle system id
  26869. * @return the corresponding system or null if none found
  26870. */
  26871. Scene.prototype.getParticleSystemByID = function (id) {
  26872. for (var index = 0; index < this.particleSystems.length; index++) {
  26873. if (this.particleSystems[index].id === id) {
  26874. return this.particleSystems[index];
  26875. }
  26876. }
  26877. return null;
  26878. };
  26879. /**
  26880. * Gets a geometry using its ID
  26881. * @param id defines the geometry's id
  26882. * @return the geometry or null if none found.
  26883. */
  26884. Scene.prototype.getGeometryByID = function (id) {
  26885. for (var index = 0; index < this._geometries.length; index++) {
  26886. if (this._geometries[index].id === id) {
  26887. return this._geometries[index];
  26888. }
  26889. }
  26890. return null;
  26891. };
  26892. /**
  26893. * Add a new geometry to this scene
  26894. * @param geometry defines the geometry to be added to the scene.
  26895. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26896. * @return a boolean defining if the geometry was added or not
  26897. */
  26898. Scene.prototype.pushGeometry = function (geometry, force) {
  26899. if (!force && this.getGeometryByID(geometry.id)) {
  26900. return false;
  26901. }
  26902. this._geometries.push(geometry);
  26903. //notify the collision coordinator
  26904. if (this.collisionCoordinator) {
  26905. this.collisionCoordinator.onGeometryAdded(geometry);
  26906. }
  26907. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26908. return true;
  26909. };
  26910. /**
  26911. * Removes an existing geometry
  26912. * @param geometry defines the geometry to be removed from the scene
  26913. * @return a boolean defining if the geometry was removed or not
  26914. */
  26915. Scene.prototype.removeGeometry = function (geometry) {
  26916. var index = this._geometries.indexOf(geometry);
  26917. if (index > -1) {
  26918. this._geometries.splice(index, 1);
  26919. //notify the collision coordinator
  26920. if (this.collisionCoordinator) {
  26921. this.collisionCoordinator.onGeometryDeleted(geometry);
  26922. }
  26923. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26924. return true;
  26925. }
  26926. return false;
  26927. };
  26928. /**
  26929. * Gets the list of geometries attached to the scene
  26930. * @returns an array of Geometry
  26931. */
  26932. Scene.prototype.getGeometries = function () {
  26933. return this._geometries;
  26934. };
  26935. /**
  26936. * Gets the first added mesh found of a given ID
  26937. * @param id defines the id to search for
  26938. * @return the mesh found or null if not found at all
  26939. */
  26940. Scene.prototype.getMeshByID = function (id) {
  26941. for (var index = 0; index < this.meshes.length; index++) {
  26942. if (this.meshes[index].id === id) {
  26943. return this.meshes[index];
  26944. }
  26945. }
  26946. return null;
  26947. };
  26948. /**
  26949. * Gets a list of meshes using their id
  26950. * @param id defines the id to search for
  26951. * @returns a list of meshes
  26952. */
  26953. Scene.prototype.getMeshesByID = function (id) {
  26954. return this.meshes.filter(function (m) {
  26955. return m.id === id;
  26956. });
  26957. };
  26958. /**
  26959. * Gets the first added transform node found of a given ID
  26960. * @param id defines the id to search for
  26961. * @return the found transform node or null if not found at all.
  26962. */
  26963. Scene.prototype.getTransformNodeByID = function (id) {
  26964. for (var index = 0; index < this.transformNodes.length; index++) {
  26965. if (this.transformNodes[index].id === id) {
  26966. return this.transformNodes[index];
  26967. }
  26968. }
  26969. return null;
  26970. };
  26971. /**
  26972. * Gets a list of transform nodes using their id
  26973. * @param id defines the id to search for
  26974. * @returns a list of transform nodes
  26975. */
  26976. Scene.prototype.getTransformNodesByID = function (id) {
  26977. return this.transformNodes.filter(function (m) {
  26978. return m.id === id;
  26979. });
  26980. };
  26981. /**
  26982. * Gets a mesh with its auto-generated unique id
  26983. * @param uniqueId defines the unique id to search for
  26984. * @return the found mesh or null if not found at all.
  26985. */
  26986. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26987. for (var index = 0; index < this.meshes.length; index++) {
  26988. if (this.meshes[index].uniqueId === uniqueId) {
  26989. return this.meshes[index];
  26990. }
  26991. }
  26992. return null;
  26993. };
  26994. /**
  26995. * Gets a the last added mesh using a given id
  26996. * @param id defines the id to search for
  26997. * @return the found mesh or null if not found at all.
  26998. */
  26999. Scene.prototype.getLastMeshByID = function (id) {
  27000. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27001. if (this.meshes[index].id === id) {
  27002. return this.meshes[index];
  27003. }
  27004. }
  27005. return null;
  27006. };
  27007. /**
  27008. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27009. * @param id defines the id to search for
  27010. * @return the found node or null if not found at all
  27011. */
  27012. Scene.prototype.getLastEntryByID = function (id) {
  27013. var index;
  27014. for (index = this.meshes.length - 1; index >= 0; index--) {
  27015. if (this.meshes[index].id === id) {
  27016. return this.meshes[index];
  27017. }
  27018. }
  27019. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27020. if (this.transformNodes[index].id === id) {
  27021. return this.transformNodes[index];
  27022. }
  27023. }
  27024. for (index = this.cameras.length - 1; index >= 0; index--) {
  27025. if (this.cameras[index].id === id) {
  27026. return this.cameras[index];
  27027. }
  27028. }
  27029. for (index = this.lights.length - 1; index >= 0; index--) {
  27030. if (this.lights[index].id === id) {
  27031. return this.lights[index];
  27032. }
  27033. }
  27034. return null;
  27035. };
  27036. /**
  27037. * Gets a node (Mesh, Camera, Light) using a given id
  27038. * @param id defines the id to search for
  27039. * @return the found node or null if not found at all
  27040. */
  27041. Scene.prototype.getNodeByID = function (id) {
  27042. var mesh = this.getMeshByID(id);
  27043. if (mesh) {
  27044. return mesh;
  27045. }
  27046. var light = this.getLightByID(id);
  27047. if (light) {
  27048. return light;
  27049. }
  27050. var camera = this.getCameraByID(id);
  27051. if (camera) {
  27052. return camera;
  27053. }
  27054. var bone = this.getBoneByID(id);
  27055. return bone;
  27056. };
  27057. /**
  27058. * Gets a node (Mesh, Camera, Light) using a given name
  27059. * @param name defines the name to search for
  27060. * @return the found node or null if not found at all.
  27061. */
  27062. Scene.prototype.getNodeByName = function (name) {
  27063. var mesh = this.getMeshByName(name);
  27064. if (mesh) {
  27065. return mesh;
  27066. }
  27067. var light = this.getLightByName(name);
  27068. if (light) {
  27069. return light;
  27070. }
  27071. var camera = this.getCameraByName(name);
  27072. if (camera) {
  27073. return camera;
  27074. }
  27075. var bone = this.getBoneByName(name);
  27076. return bone;
  27077. };
  27078. /**
  27079. * Gets a mesh using a given name
  27080. * @param name defines the name to search for
  27081. * @return the found mesh or null if not found at all.
  27082. */
  27083. Scene.prototype.getMeshByName = function (name) {
  27084. for (var index = 0; index < this.meshes.length; index++) {
  27085. if (this.meshes[index].name === name) {
  27086. return this.meshes[index];
  27087. }
  27088. }
  27089. return null;
  27090. };
  27091. /**
  27092. * Gets a transform node using a given name
  27093. * @param name defines the name to search for
  27094. * @return the found transform node or null if not found at all.
  27095. */
  27096. Scene.prototype.getTransformNodeByName = function (name) {
  27097. for (var index = 0; index < this.transformNodes.length; index++) {
  27098. if (this.transformNodes[index].name === name) {
  27099. return this.transformNodes[index];
  27100. }
  27101. }
  27102. return null;
  27103. };
  27104. /**
  27105. * Gets a sound using a given name
  27106. * @param name defines the name to search for
  27107. * @return the found sound or null if not found at all.
  27108. */
  27109. Scene.prototype.getSoundByName = function (name) {
  27110. var index;
  27111. if (BABYLON.AudioEngine) {
  27112. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27113. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27114. return this.mainSoundTrack.soundCollection[index];
  27115. }
  27116. }
  27117. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27118. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27119. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27120. return this.soundTracks[sdIndex].soundCollection[index];
  27121. }
  27122. }
  27123. }
  27124. }
  27125. return null;
  27126. };
  27127. /**
  27128. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27129. * @param id defines the id to search for
  27130. * @return the found skeleton or null if not found at all.
  27131. */
  27132. Scene.prototype.getLastSkeletonByID = function (id) {
  27133. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27134. if (this.skeletons[index].id === id) {
  27135. return this.skeletons[index];
  27136. }
  27137. }
  27138. return null;
  27139. };
  27140. /**
  27141. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27142. * @param id defines the id to search for
  27143. * @return the found skeleton or null if not found at all.
  27144. */
  27145. Scene.prototype.getSkeletonById = function (id) {
  27146. for (var index = 0; index < this.skeletons.length; index++) {
  27147. if (this.skeletons[index].id === id) {
  27148. return this.skeletons[index];
  27149. }
  27150. }
  27151. return null;
  27152. };
  27153. /**
  27154. * Gets a skeleton using a given name
  27155. * @param name defines the name to search for
  27156. * @return the found skeleton or null if not found at all.
  27157. */
  27158. Scene.prototype.getSkeletonByName = function (name) {
  27159. for (var index = 0; index < this.skeletons.length; index++) {
  27160. if (this.skeletons[index].name === name) {
  27161. return this.skeletons[index];
  27162. }
  27163. }
  27164. return null;
  27165. };
  27166. /**
  27167. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27168. * @param id defines the id to search for
  27169. * @return the found morph target manager or null if not found at all.
  27170. */
  27171. Scene.prototype.getMorphTargetManagerById = function (id) {
  27172. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27173. if (this.morphTargetManagers[index].uniqueId === id) {
  27174. return this.morphTargetManagers[index];
  27175. }
  27176. }
  27177. return null;
  27178. };
  27179. /**
  27180. * Gets a boolean indicating if the given mesh is active
  27181. * @param mesh defines the mesh to look for
  27182. * @returns true if the mesh is in the active list
  27183. */
  27184. Scene.prototype.isActiveMesh = function (mesh) {
  27185. return (this._activeMeshes.indexOf(mesh) !== -1);
  27186. };
  27187. /**
  27188. * Return a the first highlight layer of the scene with a given name.
  27189. * @param name The name of the highlight layer to look for.
  27190. * @return The highlight layer if found otherwise null.
  27191. */
  27192. Scene.prototype.getHighlightLayerByName = function (name) {
  27193. for (var index = 0; index < this.effectLayers.length; index++) {
  27194. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27195. return this.effectLayers[index];
  27196. }
  27197. }
  27198. return null;
  27199. };
  27200. /**
  27201. * Return a the first highlight layer of the scene with a given name.
  27202. * @param name The name of the highlight layer to look for.
  27203. * @return The highlight layer if found otherwise null.
  27204. */
  27205. Scene.prototype.getGlowLayerByName = function (name) {
  27206. for (var index = 0; index < this.effectLayers.length; index++) {
  27207. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27208. return this.effectLayers[index];
  27209. }
  27210. }
  27211. return null;
  27212. };
  27213. Object.defineProperty(Scene.prototype, "uid", {
  27214. /**
  27215. * Return a unique id as a string which can serve as an identifier for the scene
  27216. */
  27217. get: function () {
  27218. if (!this._uid) {
  27219. this._uid = BABYLON.Tools.RandomId();
  27220. }
  27221. return this._uid;
  27222. },
  27223. enumerable: true,
  27224. configurable: true
  27225. });
  27226. /**
  27227. * Add an externaly attached data from its key.
  27228. * This method call will fail and return false, if such key already exists.
  27229. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27230. * @param key the unique key that identifies the data
  27231. * @param data the data object to associate to the key for this Engine instance
  27232. * @return true if no such key were already present and the data was added successfully, false otherwise
  27233. */
  27234. Scene.prototype.addExternalData = function (key, data) {
  27235. if (!this._externalData) {
  27236. this._externalData = new BABYLON.StringDictionary();
  27237. }
  27238. return this._externalData.add(key, data);
  27239. };
  27240. /**
  27241. * Get an externaly attached data from its key
  27242. * @param key the unique key that identifies the data
  27243. * @return the associated data, if present (can be null), or undefined if not present
  27244. */
  27245. Scene.prototype.getExternalData = function (key) {
  27246. if (!this._externalData) {
  27247. return null;
  27248. }
  27249. return this._externalData.get(key);
  27250. };
  27251. /**
  27252. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27253. * @param key the unique key that identifies the data
  27254. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27255. * @return the associated data, can be null if the factory returned null.
  27256. */
  27257. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27258. if (!this._externalData) {
  27259. this._externalData = new BABYLON.StringDictionary();
  27260. }
  27261. return this._externalData.getOrAddWithFactory(key, factory);
  27262. };
  27263. /**
  27264. * Remove an externaly attached data from the Engine instance
  27265. * @param key the unique key that identifies the data
  27266. * @return true if the data was successfully removed, false if it doesn't exist
  27267. */
  27268. Scene.prototype.removeExternalData = function (key) {
  27269. return this._externalData.remove(key);
  27270. };
  27271. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27272. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27273. if (mesh.showSubMeshesBoundingBox) {
  27274. var boundingInfo = subMesh.getBoundingInfo();
  27275. if (boundingInfo !== null && boundingInfo !== undefined) {
  27276. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27277. }
  27278. }
  27279. var material = subMesh.getMaterial();
  27280. if (material !== null && material !== undefined) {
  27281. // Render targets
  27282. if (material.getRenderTargetTextures !== undefined) {
  27283. if (this._processedMaterials.indexOf(material) === -1) {
  27284. this._processedMaterials.push(material);
  27285. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27286. }
  27287. }
  27288. // Dispatch
  27289. this._activeIndices.addCount(subMesh.indexCount, false);
  27290. this._renderingManager.dispatch(subMesh, mesh, material);
  27291. }
  27292. }
  27293. };
  27294. /**
  27295. * Clear the processed materials smart array preventing retention point in material dispose.
  27296. */
  27297. Scene.prototype.freeProcessedMaterials = function () {
  27298. this._processedMaterials.dispose();
  27299. };
  27300. /**
  27301. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27302. */
  27303. Scene.prototype.freeActiveMeshes = function () {
  27304. this._activeMeshes.dispose();
  27305. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27306. this.activeCamera._activeMeshes.dispose();
  27307. }
  27308. if (this.activeCameras) {
  27309. for (var i = 0; i < this.activeCameras.length; i++) {
  27310. var activeCamera = this.activeCameras[i];
  27311. if (activeCamera && activeCamera._activeMeshes) {
  27312. activeCamera._activeMeshes.dispose();
  27313. }
  27314. }
  27315. }
  27316. };
  27317. /**
  27318. * Clear the info related to rendering groups preventing retention points during dispose.
  27319. */
  27320. Scene.prototype.freeRenderingGroups = function () {
  27321. if (this._renderingManager) {
  27322. this._renderingManager.freeRenderingGroups();
  27323. }
  27324. if (this.textures) {
  27325. for (var i = 0; i < this.textures.length; i++) {
  27326. var texture = this.textures[i];
  27327. if (texture && texture.renderList) {
  27328. texture.freeRenderingGroups();
  27329. }
  27330. }
  27331. }
  27332. };
  27333. /** @hidden */
  27334. Scene.prototype._isInIntermediateRendering = function () {
  27335. return this._intermediateRendering;
  27336. };
  27337. /**
  27338. * Defines the current active mesh candidate provider
  27339. * @param provider defines the provider to use
  27340. */
  27341. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27342. this._activeMeshCandidateProvider = provider;
  27343. };
  27344. /**
  27345. * Gets the current active mesh candidate provider
  27346. * @returns the current active mesh candidate provider
  27347. */
  27348. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27349. return this._activeMeshCandidateProvider;
  27350. };
  27351. /**
  27352. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27353. * @returns the current scene
  27354. */
  27355. Scene.prototype.freezeActiveMeshes = function () {
  27356. if (!this.activeCamera) {
  27357. return this;
  27358. }
  27359. if (!this._frustumPlanes) {
  27360. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27361. }
  27362. this._evaluateActiveMeshes();
  27363. this._activeMeshesFrozen = true;
  27364. return this;
  27365. };
  27366. /**
  27367. * Use this function to restart evaluating active meshes on every frame
  27368. * @returns the current scene
  27369. */
  27370. Scene.prototype.unfreezeActiveMeshes = function () {
  27371. this._activeMeshesFrozen = false;
  27372. return this;
  27373. };
  27374. Scene.prototype._evaluateActiveMeshes = function () {
  27375. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27376. return;
  27377. }
  27378. if (!this.activeCamera) {
  27379. return;
  27380. }
  27381. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27382. this.activeCamera._activeMeshes.reset();
  27383. this._activeMeshes.reset();
  27384. this._renderingManager.reset();
  27385. this._processedMaterials.reset();
  27386. this._activeParticleSystems.reset();
  27387. this._activeSkeletons.reset();
  27388. this._softwareSkinnedMeshes.reset();
  27389. if (this._boundingBoxRenderer) {
  27390. this._boundingBoxRenderer.reset();
  27391. }
  27392. // Meshes
  27393. var meshes;
  27394. var len;
  27395. var checkIsEnabled = true;
  27396. // Determine mesh candidates
  27397. if (this._activeMeshCandidateProvider !== undefined) {
  27398. // Use _activeMeshCandidateProvider
  27399. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27400. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27401. if (meshes !== undefined) {
  27402. len = meshes.length;
  27403. }
  27404. else {
  27405. len = 0;
  27406. }
  27407. }
  27408. else if (this._selectionOctree !== undefined) {
  27409. // Octree
  27410. var selection = this._selectionOctree.select(this._frustumPlanes);
  27411. meshes = selection.data;
  27412. len = selection.length;
  27413. }
  27414. else {
  27415. // Full scene traversal
  27416. len = this.meshes.length;
  27417. meshes = this.meshes;
  27418. }
  27419. // Check each mesh
  27420. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27421. mesh = meshes[meshIndex];
  27422. if (mesh.isBlocked) {
  27423. continue;
  27424. }
  27425. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27426. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27427. continue;
  27428. }
  27429. mesh.computeWorldMatrix();
  27430. // Intersections
  27431. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27432. this._meshesForIntersections.pushNoDuplicate(mesh);
  27433. }
  27434. // Switch to current LOD
  27435. meshLOD = mesh.getLOD(this.activeCamera);
  27436. if (meshLOD === undefined || meshLOD === null) {
  27437. continue;
  27438. }
  27439. mesh._preActivate();
  27440. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27441. this._activeMeshes.push(mesh);
  27442. this.activeCamera._activeMeshes.push(mesh);
  27443. mesh._activate(this._renderId);
  27444. if (meshLOD !== mesh) {
  27445. meshLOD._activate(this._renderId);
  27446. }
  27447. this._activeMesh(mesh, meshLOD);
  27448. }
  27449. }
  27450. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27451. // Particle systems
  27452. if (this.particlesEnabled) {
  27453. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27454. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27455. var particleSystem = this.particleSystems[particleIndex];
  27456. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27457. continue;
  27458. }
  27459. var emitter = particleSystem.emitter;
  27460. if (!emitter.position || emitter.isEnabled()) {
  27461. this._activeParticleSystems.push(particleSystem);
  27462. particleSystem.animate();
  27463. this._renderingManager.dispatchParticles(particleSystem);
  27464. }
  27465. }
  27466. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27467. }
  27468. };
  27469. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27470. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27471. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27472. mesh.skeleton.prepare();
  27473. }
  27474. if (!mesh.computeBonesUsingShaders) {
  27475. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27476. }
  27477. }
  27478. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27479. var boundingInfo = sourceMesh.getBoundingInfo();
  27480. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27481. }
  27482. if (mesh !== undefined && mesh !== null
  27483. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27484. // Submeshes Octrees
  27485. var len;
  27486. var subMeshes;
  27487. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27488. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27489. len = intersections.length;
  27490. subMeshes = intersections.data;
  27491. }
  27492. else {
  27493. subMeshes = mesh.subMeshes;
  27494. len = subMeshes.length;
  27495. }
  27496. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27497. subMesh = subMeshes[subIndex];
  27498. this._evaluateSubMesh(subMesh, mesh);
  27499. }
  27500. }
  27501. };
  27502. /**
  27503. * Update the transform matrix to update from the current active camera
  27504. * @param force defines a boolean used to force the update even if cache is up to date
  27505. */
  27506. Scene.prototype.updateTransformMatrix = function (force) {
  27507. if (!this.activeCamera) {
  27508. return;
  27509. }
  27510. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27511. };
  27512. /**
  27513. * 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)
  27514. * @param alternateCamera defines the camera to use
  27515. */
  27516. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27517. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27518. };
  27519. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27520. if (camera && camera._skipRendering) {
  27521. return;
  27522. }
  27523. var engine = this._engine;
  27524. this.activeCamera = camera;
  27525. if (!this.activeCamera)
  27526. throw new Error("Active camera not set");
  27527. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27528. // Viewport
  27529. engine.setViewport(this.activeCamera.viewport);
  27530. // Camera
  27531. this.resetCachedMaterial();
  27532. this._renderId++;
  27533. this.updateTransformMatrix();
  27534. if (camera._alternateCamera) {
  27535. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27536. this._alternateRendering = true;
  27537. }
  27538. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27539. // Meshes
  27540. this._evaluateActiveMeshes();
  27541. // Software skinning
  27542. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27543. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27544. mesh.applySkeleton(mesh.skeleton);
  27545. }
  27546. // Render targets
  27547. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27548. var needsRestoreFrameBuffer = false;
  27549. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27550. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27551. }
  27552. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27553. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27554. }
  27555. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27556. this._intermediateRendering = true;
  27557. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27558. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27559. var renderTarget = this._renderTargets.data[renderIndex];
  27560. if (renderTarget._shouldRender()) {
  27561. this._renderId++;
  27562. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27563. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27564. }
  27565. }
  27566. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27567. this._intermediateRendering = false;
  27568. this._renderId++;
  27569. needsRestoreFrameBuffer = true; // Restore back buffer
  27570. }
  27571. // Render EffecttLayer Texture
  27572. var stencilState = this._engine.getStencilBuffer();
  27573. var renderEffects = false;
  27574. var needStencil = false;
  27575. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27576. this._intermediateRendering = true;
  27577. for (var i = 0; i < this.effectLayers.length; i++) {
  27578. var effectLayer = this.effectLayers[i];
  27579. if (effectLayer.shouldRender() &&
  27580. (!effectLayer.camera ||
  27581. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27582. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27583. renderEffects = true;
  27584. needStencil = needStencil || effectLayer.needStencil();
  27585. var renderTarget = effectLayer._mainTexture;
  27586. if (renderTarget._shouldRender()) {
  27587. this._renderId++;
  27588. renderTarget.render(false, false);
  27589. needsRestoreFrameBuffer = true;
  27590. }
  27591. }
  27592. }
  27593. this._intermediateRendering = false;
  27594. this._renderId++;
  27595. }
  27596. if (needsRestoreFrameBuffer) {
  27597. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27598. }
  27599. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27600. // Prepare Frame
  27601. this.postProcessManager._prepareFrame();
  27602. // Backgrounds
  27603. var layerIndex;
  27604. var layer;
  27605. if (this.layers.length) {
  27606. engine.setDepthBuffer(false);
  27607. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27608. layer = this.layers[layerIndex];
  27609. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27610. layer.render();
  27611. }
  27612. }
  27613. engine.setDepthBuffer(true);
  27614. }
  27615. // Activate effect Layer stencil
  27616. if (needStencil) {
  27617. this._engine.setStencilBuffer(true);
  27618. }
  27619. // Render
  27620. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27621. this._renderingManager.render(null, null, true, true);
  27622. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27623. // Restore effect Layer stencil
  27624. if (needStencil) {
  27625. this._engine.setStencilBuffer(stencilState);
  27626. }
  27627. // Bounding boxes
  27628. if (this._boundingBoxRenderer) {
  27629. this._boundingBoxRenderer.render();
  27630. }
  27631. // Lens flares
  27632. if (this.lensFlaresEnabled) {
  27633. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27634. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27635. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27636. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27637. lensFlareSystem.render();
  27638. }
  27639. }
  27640. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27641. }
  27642. // Effect Layer
  27643. if (renderEffects) {
  27644. engine.setDepthBuffer(false);
  27645. for (var i = 0; i < this.effectLayers.length; i++) {
  27646. if (this.effectLayers[i].shouldRender()) {
  27647. this.effectLayers[i].render();
  27648. }
  27649. }
  27650. engine.setDepthBuffer(true);
  27651. }
  27652. // Foregrounds
  27653. if (this.layers.length) {
  27654. engine.setDepthBuffer(false);
  27655. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27656. layer = this.layers[layerIndex];
  27657. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27658. layer.render();
  27659. }
  27660. }
  27661. engine.setDepthBuffer(true);
  27662. }
  27663. // Finalize frame
  27664. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27665. // Reset some special arrays
  27666. this._renderTargets.reset();
  27667. this._alternateRendering = false;
  27668. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27669. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27670. };
  27671. Scene.prototype._processSubCameras = function (camera) {
  27672. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27673. this._renderForCamera(camera);
  27674. return;
  27675. }
  27676. // rig cameras
  27677. for (var index = 0; index < camera._rigCameras.length; index++) {
  27678. this._renderForCamera(camera._rigCameras[index], camera);
  27679. }
  27680. this.activeCamera = camera;
  27681. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27682. };
  27683. Scene.prototype._checkIntersections = function () {
  27684. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27685. var sourceMesh = this._meshesForIntersections.data[index];
  27686. if (!sourceMesh.actionManager) {
  27687. continue;
  27688. }
  27689. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27690. var action = sourceMesh.actionManager.actions[actionIndex];
  27691. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27692. var parameters = action.getTriggerParameter();
  27693. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27694. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27695. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27696. if (areIntersecting && currentIntersectionInProgress === -1) {
  27697. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27698. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27699. sourceMesh._intersectionsInProgress.push(otherMesh);
  27700. }
  27701. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27702. sourceMesh._intersectionsInProgress.push(otherMesh);
  27703. }
  27704. }
  27705. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27706. //They intersected, and now they don't.
  27707. //is this trigger an exit trigger? execute an event.
  27708. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27709. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27710. }
  27711. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27712. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27713. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27714. return otherMesh === parameterMesh;
  27715. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27716. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27717. }
  27718. }
  27719. }
  27720. }
  27721. }
  27722. };
  27723. /**
  27724. * Render the scene
  27725. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27726. */
  27727. Scene.prototype.render = function (updateCameras) {
  27728. if (updateCameras === void 0) { updateCameras = true; }
  27729. if (this.isDisposed) {
  27730. return;
  27731. }
  27732. this._activeParticles.fetchNewFrame();
  27733. this._totalVertices.fetchNewFrame();
  27734. this._activeIndices.fetchNewFrame();
  27735. this._activeBones.fetchNewFrame();
  27736. this._meshesForIntersections.reset();
  27737. this.resetCachedMaterial();
  27738. this.onBeforeAnimationsObservable.notifyObservers(this);
  27739. // Actions
  27740. if (this.actionManager) {
  27741. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27742. }
  27743. //Simplification Queue
  27744. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27745. this.simplificationQueue.executeNext();
  27746. }
  27747. if (this._engine.isDeterministicLockStep()) {
  27748. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27749. var defaultFPS = (60.0 / 1000.0);
  27750. var defaultFrameTime = 1000 / 60; // frame time in MS
  27751. if (this._physicsEngine) {
  27752. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27753. }
  27754. var stepsTaken = 0;
  27755. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27756. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27757. internalSteps = Math.min(internalSteps, maxSubSteps);
  27758. do {
  27759. this.onBeforeStepObservable.notifyObservers(this);
  27760. // Animations
  27761. this._animationRatio = defaultFrameTime * defaultFPS;
  27762. this._animate();
  27763. this.onAfterAnimationsObservable.notifyObservers(this);
  27764. // Physics
  27765. if (this._physicsEngine) {
  27766. this.onBeforePhysicsObservable.notifyObservers(this);
  27767. this._physicsEngine._step(defaultFrameTime / 1000);
  27768. this.onAfterPhysicsObservable.notifyObservers(this);
  27769. }
  27770. this.onAfterStepObservable.notifyObservers(this);
  27771. this._currentStepId++;
  27772. stepsTaken++;
  27773. deltaTime -= defaultFrameTime;
  27774. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27775. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27776. }
  27777. else {
  27778. // Animations
  27779. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27780. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27781. this._animate();
  27782. this.onAfterAnimationsObservable.notifyObservers(this);
  27783. // Physics
  27784. if (this._physicsEngine) {
  27785. this.onBeforePhysicsObservable.notifyObservers(this);
  27786. this._physicsEngine._step(deltaTime / 1000.0);
  27787. this.onAfterPhysicsObservable.notifyObservers(this);
  27788. }
  27789. }
  27790. // update gamepad manager
  27791. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27792. this._gamepadManager._checkGamepadsStatus();
  27793. }
  27794. // Update Cameras
  27795. if (updateCameras) {
  27796. if (this.activeCameras.length > 0) {
  27797. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27798. var camera = this.activeCameras[cameraIndex];
  27799. camera.update();
  27800. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27801. // rig cameras
  27802. for (var index = 0; index < camera._rigCameras.length; index++) {
  27803. camera._rigCameras[index].update();
  27804. }
  27805. }
  27806. }
  27807. }
  27808. else if (this.activeCamera) {
  27809. this.activeCamera.update();
  27810. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27811. // rig cameras
  27812. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27813. this.activeCamera._rigCameras[index].update();
  27814. }
  27815. }
  27816. }
  27817. }
  27818. // Before render
  27819. this.onBeforeRenderObservable.notifyObservers(this);
  27820. // Customs render targets
  27821. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27822. var engine = this.getEngine();
  27823. var currentActiveCamera = this.activeCamera;
  27824. if (this.renderTargetsEnabled) {
  27825. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27826. this._intermediateRendering = true;
  27827. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27828. var renderTarget = this.customRenderTargets[customIndex];
  27829. if (renderTarget._shouldRender()) {
  27830. this._renderId++;
  27831. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27832. if (!this.activeCamera)
  27833. throw new Error("Active camera not set");
  27834. // Viewport
  27835. engine.setViewport(this.activeCamera.viewport);
  27836. // Camera
  27837. this.updateTransformMatrix();
  27838. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27839. }
  27840. }
  27841. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27842. this._intermediateRendering = false;
  27843. this._renderId++;
  27844. }
  27845. // Restore back buffer
  27846. if (this.customRenderTargets.length > 0) {
  27847. engine.restoreDefaultFramebuffer();
  27848. }
  27849. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27850. this.activeCamera = currentActiveCamera;
  27851. // Procedural textures
  27852. if (this.proceduralTexturesEnabled) {
  27853. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27854. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27855. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27856. if (proceduralTexture._shouldRender()) {
  27857. proceduralTexture.render();
  27858. }
  27859. }
  27860. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27861. }
  27862. // Clear
  27863. if (this.autoClearDepthAndStencil || this.autoClear) {
  27864. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27865. }
  27866. // Shadows
  27867. if (this.shadowsEnabled) {
  27868. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27869. var light = this.lights[lightIndex];
  27870. var shadowGenerator = light.getShadowGenerator();
  27871. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27872. var shadowMap = (shadowGenerator.getShadowMap());
  27873. if (this.textures.indexOf(shadowMap) !== -1) {
  27874. this._renderTargets.push(shadowMap);
  27875. }
  27876. }
  27877. }
  27878. }
  27879. // Depth renderer
  27880. for (var key in this._depthRenderer) {
  27881. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27882. }
  27883. // Geometry renderer
  27884. if (this._geometryBufferRenderer) {
  27885. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27886. }
  27887. // RenderPipeline
  27888. if (this._postProcessRenderPipelineManager) {
  27889. this._postProcessRenderPipelineManager.update();
  27890. }
  27891. // Multi-cameras?
  27892. if (this.activeCameras.length > 0) {
  27893. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27894. if (cameraIndex > 0) {
  27895. this._engine.clear(null, false, true, true);
  27896. }
  27897. this._processSubCameras(this.activeCameras[cameraIndex]);
  27898. }
  27899. }
  27900. else {
  27901. if (!this.activeCamera) {
  27902. throw new Error("No camera defined");
  27903. }
  27904. this._processSubCameras(this.activeCamera);
  27905. }
  27906. // Intersection checks
  27907. this._checkIntersections();
  27908. // Update the audio listener attached to the camera
  27909. if (BABYLON.AudioEngine) {
  27910. this._updateAudioParameters();
  27911. }
  27912. // After render
  27913. if (this.afterRender) {
  27914. this.afterRender();
  27915. }
  27916. this.onAfterRenderObservable.notifyObservers(this);
  27917. // Cleaning
  27918. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27919. var data = this._toBeDisposed.data[index];
  27920. if (data) {
  27921. data.dispose();
  27922. }
  27923. this._toBeDisposed[index] = null;
  27924. }
  27925. this._toBeDisposed.reset();
  27926. if (this.dumpNextRenderTargets) {
  27927. this.dumpNextRenderTargets = false;
  27928. }
  27929. this._activeBones.addCount(0, true);
  27930. this._activeIndices.addCount(0, true);
  27931. this._activeParticles.addCount(0, true);
  27932. };
  27933. Scene.prototype._updateAudioParameters = function () {
  27934. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27935. return;
  27936. }
  27937. var listeningCamera;
  27938. var audioEngine = BABYLON.Engine.audioEngine;
  27939. if (this.activeCameras.length > 0) {
  27940. listeningCamera = this.activeCameras[0];
  27941. }
  27942. else {
  27943. listeningCamera = this.activeCamera;
  27944. }
  27945. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27946. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27947. // for VR cameras
  27948. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27949. listeningCamera = listeningCamera.rigCameras[0];
  27950. }
  27951. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27952. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27953. cameraDirection.normalize();
  27954. // To avoid some errors on GearVR
  27955. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27956. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27957. }
  27958. var i;
  27959. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27960. var sound = this.mainSoundTrack.soundCollection[i];
  27961. if (sound.useCustomAttenuation) {
  27962. sound.updateDistanceFromListener();
  27963. }
  27964. }
  27965. for (i = 0; i < this.soundTracks.length; i++) {
  27966. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27967. sound = this.soundTracks[i].soundCollection[j];
  27968. if (sound.useCustomAttenuation) {
  27969. sound.updateDistanceFromListener();
  27970. }
  27971. }
  27972. }
  27973. }
  27974. };
  27975. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27976. // Audio
  27977. /**
  27978. * Gets or sets if audio support is enabled
  27979. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27980. */
  27981. get: function () {
  27982. return this._audioEnabled;
  27983. },
  27984. set: function (value) {
  27985. this._audioEnabled = value;
  27986. if (BABYLON.AudioEngine) {
  27987. if (this._audioEnabled) {
  27988. this._enableAudio();
  27989. }
  27990. else {
  27991. this._disableAudio();
  27992. }
  27993. }
  27994. },
  27995. enumerable: true,
  27996. configurable: true
  27997. });
  27998. Scene.prototype._disableAudio = function () {
  27999. var i;
  28000. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28001. this.mainSoundTrack.soundCollection[i].pause();
  28002. }
  28003. for (i = 0; i < this.soundTracks.length; i++) {
  28004. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28005. this.soundTracks[i].soundCollection[j].pause();
  28006. }
  28007. }
  28008. };
  28009. Scene.prototype._enableAudio = function () {
  28010. var i;
  28011. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28012. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28013. this.mainSoundTrack.soundCollection[i].play();
  28014. }
  28015. }
  28016. for (i = 0; i < this.soundTracks.length; i++) {
  28017. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28018. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28019. this.soundTracks[i].soundCollection[j].play();
  28020. }
  28021. }
  28022. }
  28023. };
  28024. Object.defineProperty(Scene.prototype, "headphone", {
  28025. /**
  28026. * Gets or sets if audio will be output to headphones
  28027. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28028. */
  28029. get: function () {
  28030. return this._headphone;
  28031. },
  28032. set: function (value) {
  28033. this._headphone = value;
  28034. if (BABYLON.AudioEngine) {
  28035. if (this._headphone) {
  28036. this._switchAudioModeForHeadphones();
  28037. }
  28038. else {
  28039. this._switchAudioModeForNormalSpeakers();
  28040. }
  28041. }
  28042. },
  28043. enumerable: true,
  28044. configurable: true
  28045. });
  28046. Scene.prototype._switchAudioModeForHeadphones = function () {
  28047. this.mainSoundTrack.switchPanningModelToHRTF();
  28048. for (var i = 0; i < this.soundTracks.length; i++) {
  28049. this.soundTracks[i].switchPanningModelToHRTF();
  28050. }
  28051. };
  28052. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28053. this.mainSoundTrack.switchPanningModelToEqualPower();
  28054. for (var i = 0; i < this.soundTracks.length; i++) {
  28055. this.soundTracks[i].switchPanningModelToEqualPower();
  28056. }
  28057. };
  28058. /**
  28059. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28060. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28061. * @returns the created depth renderer
  28062. */
  28063. Scene.prototype.enableDepthRenderer = function (camera) {
  28064. camera = camera || this.activeCamera;
  28065. if (!camera) {
  28066. throw "No camera available to enable depth renderer";
  28067. }
  28068. if (!this._depthRenderer[camera.id]) {
  28069. var textureType = 0;
  28070. if (this._engine.getCaps().textureHalfFloatRender) {
  28071. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28072. }
  28073. else if (this._engine.getCaps().textureFloatRender) {
  28074. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28075. }
  28076. else {
  28077. throw "Depth renderer does not support int texture type";
  28078. }
  28079. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28080. }
  28081. return this._depthRenderer[camera.id];
  28082. };
  28083. /**
  28084. * Disables a depth renderer for a given camera
  28085. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28086. */
  28087. Scene.prototype.disableDepthRenderer = function (camera) {
  28088. camera = camera || this.activeCamera;
  28089. if (!camera || !this._depthRenderer[camera.id]) {
  28090. return;
  28091. }
  28092. this._depthRenderer[camera.id].dispose();
  28093. delete this._depthRenderer[camera.id];
  28094. };
  28095. /**
  28096. * Enables a GeometryBufferRender and associates it with the scene
  28097. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28098. * @returns the GeometryBufferRenderer
  28099. */
  28100. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28101. if (ratio === void 0) { ratio = 1; }
  28102. if (this._geometryBufferRenderer) {
  28103. return this._geometryBufferRenderer;
  28104. }
  28105. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28106. if (!this._geometryBufferRenderer.isSupported) {
  28107. this._geometryBufferRenderer = null;
  28108. }
  28109. return this._geometryBufferRenderer;
  28110. };
  28111. /**
  28112. * Disables the GeometryBufferRender associated with the scene
  28113. */
  28114. Scene.prototype.disableGeometryBufferRenderer = function () {
  28115. if (!this._geometryBufferRenderer) {
  28116. return;
  28117. }
  28118. this._geometryBufferRenderer.dispose();
  28119. this._geometryBufferRenderer = null;
  28120. };
  28121. /**
  28122. * Freeze all materials
  28123. * A frozen material will not be updatable but should be faster to render
  28124. */
  28125. Scene.prototype.freezeMaterials = function () {
  28126. for (var i = 0; i < this.materials.length; i++) {
  28127. this.materials[i].freeze();
  28128. }
  28129. };
  28130. /**
  28131. * Unfreeze all materials
  28132. * A frozen material will not be updatable but should be faster to render
  28133. */
  28134. Scene.prototype.unfreezeMaterials = function () {
  28135. for (var i = 0; i < this.materials.length; i++) {
  28136. this.materials[i].unfreeze();
  28137. }
  28138. };
  28139. /**
  28140. * Releases all held ressources
  28141. */
  28142. Scene.prototype.dispose = function () {
  28143. this.beforeRender = null;
  28144. this.afterRender = null;
  28145. this.skeletons = [];
  28146. this.morphTargetManagers = [];
  28147. this.importedMeshesFiles = new Array();
  28148. this.stopAllAnimations();
  28149. this.resetCachedMaterial();
  28150. for (var key in this._depthRenderer) {
  28151. this._depthRenderer[key].dispose();
  28152. }
  28153. if (this._gamepadManager) {
  28154. this._gamepadManager.dispose();
  28155. this._gamepadManager = null;
  28156. }
  28157. // Smart arrays
  28158. if (this.activeCamera) {
  28159. this.activeCamera._activeMeshes.dispose();
  28160. this.activeCamera = null;
  28161. }
  28162. this._activeMeshes.dispose();
  28163. this._renderingManager.dispose();
  28164. this._processedMaterials.dispose();
  28165. this._activeParticleSystems.dispose();
  28166. this._activeSkeletons.dispose();
  28167. this._softwareSkinnedMeshes.dispose();
  28168. this._renderTargets.dispose();
  28169. this._registeredForLateAnimationBindings.dispose();
  28170. if (this._boundingBoxRenderer) {
  28171. this._boundingBoxRenderer.dispose();
  28172. }
  28173. this._meshesForIntersections.dispose();
  28174. this._toBeDisposed.dispose();
  28175. // Abort active requests
  28176. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28177. var request = _a[_i];
  28178. request.abort();
  28179. }
  28180. // Debug layer
  28181. if (this._debugLayer) {
  28182. this._debugLayer.hide();
  28183. }
  28184. // Events
  28185. this.onDisposeObservable.notifyObservers(this);
  28186. this.onDisposeObservable.clear();
  28187. this.onBeforeRenderObservable.clear();
  28188. this.onAfterRenderObservable.clear();
  28189. this.onBeforeRenderTargetsRenderObservable.clear();
  28190. this.onAfterRenderTargetsRenderObservable.clear();
  28191. this.onAfterStepObservable.clear();
  28192. this.onBeforeStepObservable.clear();
  28193. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28194. this.onAfterActiveMeshesEvaluationObservable.clear();
  28195. this.onBeforeParticlesRenderingObservable.clear();
  28196. this.onAfterParticlesRenderingObservable.clear();
  28197. this.onBeforeSpritesRenderingObservable.clear();
  28198. this.onAfterSpritesRenderingObservable.clear();
  28199. this.onBeforeDrawPhaseObservable.clear();
  28200. this.onAfterDrawPhaseObservable.clear();
  28201. this.onBeforePhysicsObservable.clear();
  28202. this.onAfterPhysicsObservable.clear();
  28203. this.onBeforeAnimationsObservable.clear();
  28204. this.onAfterAnimationsObservable.clear();
  28205. this.onDataLoadedObservable.clear();
  28206. this.detachControl();
  28207. // Release sounds & sounds tracks
  28208. if (BABYLON.AudioEngine) {
  28209. this.disposeSounds();
  28210. }
  28211. // VR Helper
  28212. if (this.VRHelper) {
  28213. this.VRHelper.dispose();
  28214. }
  28215. // Detach cameras
  28216. var canvas = this._engine.getRenderingCanvas();
  28217. if (canvas) {
  28218. var index;
  28219. for (index = 0; index < this.cameras.length; index++) {
  28220. this.cameras[index].detachControl(canvas);
  28221. }
  28222. }
  28223. // Release animation groups
  28224. while (this.animationGroups.length) {
  28225. this.animationGroups[0].dispose();
  28226. }
  28227. // Release lights
  28228. while (this.lights.length) {
  28229. this.lights[0].dispose();
  28230. }
  28231. // Release meshes
  28232. while (this.meshes.length) {
  28233. this.meshes[0].dispose(true);
  28234. }
  28235. while (this.transformNodes.length) {
  28236. this.removeTransformNode(this.transformNodes[0]);
  28237. }
  28238. // Release cameras
  28239. while (this.cameras.length) {
  28240. this.cameras[0].dispose();
  28241. }
  28242. // Release materials
  28243. if (this.defaultMaterial) {
  28244. this.defaultMaterial.dispose();
  28245. }
  28246. while (this.multiMaterials.length) {
  28247. this.multiMaterials[0].dispose();
  28248. }
  28249. while (this.materials.length) {
  28250. this.materials[0].dispose();
  28251. }
  28252. // Release particles
  28253. while (this.particleSystems.length) {
  28254. this.particleSystems[0].dispose();
  28255. }
  28256. // Release sprites
  28257. while (this.spriteManagers.length) {
  28258. this.spriteManagers[0].dispose();
  28259. }
  28260. // Release postProcesses
  28261. while (this.postProcesses.length) {
  28262. this.postProcesses[0].dispose();
  28263. }
  28264. // Release layers
  28265. while (this.layers.length) {
  28266. this.layers[0].dispose();
  28267. }
  28268. while (this.effectLayers.length) {
  28269. this.effectLayers[0].dispose();
  28270. }
  28271. // Release textures
  28272. while (this.textures.length) {
  28273. this.textures[0].dispose();
  28274. }
  28275. // Release UBO
  28276. this._sceneUbo.dispose();
  28277. if (this._alternateSceneUbo) {
  28278. this._alternateSceneUbo.dispose();
  28279. }
  28280. // Post-processes
  28281. this.postProcessManager.dispose();
  28282. if (this._postProcessRenderPipelineManager) {
  28283. this._postProcessRenderPipelineManager.dispose();
  28284. }
  28285. // Physics
  28286. if (this._physicsEngine) {
  28287. this.disablePhysicsEngine();
  28288. }
  28289. // Remove from engine
  28290. index = this._engine.scenes.indexOf(this);
  28291. if (index > -1) {
  28292. this._engine.scenes.splice(index, 1);
  28293. }
  28294. this._engine.wipeCaches(true);
  28295. this._isDisposed = true;
  28296. };
  28297. Object.defineProperty(Scene.prototype, "isDisposed", {
  28298. /**
  28299. * Gets if the scene is already disposed
  28300. */
  28301. get: function () {
  28302. return this._isDisposed;
  28303. },
  28304. enumerable: true,
  28305. configurable: true
  28306. });
  28307. /**
  28308. * Releases sounds & soundtracks
  28309. */
  28310. Scene.prototype.disposeSounds = function () {
  28311. if (!this._mainSoundTrack) {
  28312. return;
  28313. }
  28314. this.mainSoundTrack.dispose();
  28315. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28316. this.soundTracks[scIndex].dispose();
  28317. }
  28318. };
  28319. /**
  28320. * Call this function to reduce memory footprint of the scene.
  28321. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28322. */
  28323. Scene.prototype.clearCachedVertexData = function () {
  28324. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28325. var mesh = this.meshes[meshIndex];
  28326. var geometry = mesh.geometry;
  28327. if (geometry) {
  28328. geometry._indices = [];
  28329. for (var vbName in geometry._vertexBuffers) {
  28330. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28331. continue;
  28332. }
  28333. geometry._vertexBuffers[vbName]._buffer._data = null;
  28334. }
  28335. }
  28336. }
  28337. };
  28338. /**
  28339. * This function will remove the local cached buffer data from texture.
  28340. * It will save memory but will prevent the texture from being rebuilt
  28341. */
  28342. Scene.prototype.cleanCachedTextureBuffer = function () {
  28343. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28344. var baseTexture = _a[_i];
  28345. var buffer = baseTexture._buffer;
  28346. if (buffer) {
  28347. baseTexture._buffer = null;
  28348. }
  28349. }
  28350. };
  28351. // Octrees
  28352. /**
  28353. * Get the world extend vectors with an optional filter
  28354. *
  28355. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28356. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28357. */
  28358. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28359. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28360. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28361. filterPredicate = filterPredicate || (function () { return true; });
  28362. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28363. mesh.computeWorldMatrix(true);
  28364. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28365. return;
  28366. }
  28367. var boundingInfo = mesh.getBoundingInfo();
  28368. var minBox = boundingInfo.boundingBox.minimumWorld;
  28369. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28370. BABYLON.Tools.CheckExtends(minBox, min, max);
  28371. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28372. });
  28373. return {
  28374. min: min,
  28375. max: max
  28376. };
  28377. };
  28378. /**
  28379. * Creates or updates the octree used to boost selection (picking)
  28380. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28381. * @param maxCapacity defines the maximum capacity per leaf
  28382. * @param maxDepth defines the maximum depth of the octree
  28383. * @returns an octree of AbstractMesh
  28384. */
  28385. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28386. if (maxCapacity === void 0) { maxCapacity = 64; }
  28387. if (maxDepth === void 0) { maxDepth = 2; }
  28388. if (!this._selectionOctree) {
  28389. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28390. }
  28391. var worldExtends = this.getWorldExtends();
  28392. // Update octree
  28393. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28394. return this._selectionOctree;
  28395. };
  28396. // Picking
  28397. /**
  28398. * Creates a ray that can be used to pick in the scene
  28399. * @param x defines the x coordinate of the origin (on-screen)
  28400. * @param y defines the y coordinate of the origin (on-screen)
  28401. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28402. * @param camera defines the camera to use for the picking
  28403. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28404. * @returns a Ray
  28405. */
  28406. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28407. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28408. var result = BABYLON.Ray.Zero();
  28409. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28410. return result;
  28411. };
  28412. /**
  28413. * Creates a ray that can be used to pick in the scene
  28414. * @param x defines the x coordinate of the origin (on-screen)
  28415. * @param y defines the y coordinate of the origin (on-screen)
  28416. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28417. * @param result defines the ray where to store the picking ray
  28418. * @param camera defines the camera to use for the picking
  28419. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28420. * @returns the current scene
  28421. */
  28422. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28423. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28424. var engine = this._engine;
  28425. if (!camera) {
  28426. if (!this.activeCamera)
  28427. throw new Error("Active camera not set");
  28428. camera = this.activeCamera;
  28429. }
  28430. var cameraViewport = camera.viewport;
  28431. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28432. // Moving coordinates to local viewport world
  28433. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28434. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28435. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28436. return this;
  28437. };
  28438. /**
  28439. * Creates a ray that can be used to pick in the scene
  28440. * @param x defines the x coordinate of the origin (on-screen)
  28441. * @param y defines the y coordinate of the origin (on-screen)
  28442. * @param camera defines the camera to use for the picking
  28443. * @returns a Ray
  28444. */
  28445. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28446. var result = BABYLON.Ray.Zero();
  28447. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28448. return result;
  28449. };
  28450. /**
  28451. * Creates a ray that can be used to pick in the scene
  28452. * @param x defines the x coordinate of the origin (on-screen)
  28453. * @param y defines the y coordinate of the origin (on-screen)
  28454. * @param result defines the ray where to store the picking ray
  28455. * @param camera defines the camera to use for the picking
  28456. * @returns the current scene
  28457. */
  28458. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28459. if (!BABYLON.PickingInfo) {
  28460. return this;
  28461. }
  28462. var engine = this._engine;
  28463. if (!camera) {
  28464. if (!this.activeCamera)
  28465. throw new Error("Active camera not set");
  28466. camera = this.activeCamera;
  28467. }
  28468. var cameraViewport = camera.viewport;
  28469. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28470. var identity = BABYLON.Matrix.Identity();
  28471. // Moving coordinates to local viewport world
  28472. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28473. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28474. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28475. return this;
  28476. };
  28477. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28478. if (!BABYLON.PickingInfo) {
  28479. return null;
  28480. }
  28481. var pickingInfo = null;
  28482. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28483. var mesh = this.meshes[meshIndex];
  28484. if (predicate) {
  28485. if (!predicate(mesh)) {
  28486. continue;
  28487. }
  28488. }
  28489. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28490. continue;
  28491. }
  28492. var world = mesh.getWorldMatrix();
  28493. var ray = rayFunction(world);
  28494. var result = mesh.intersects(ray, fastCheck);
  28495. if (!result || !result.hit)
  28496. continue;
  28497. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28498. continue;
  28499. pickingInfo = result;
  28500. if (fastCheck) {
  28501. break;
  28502. }
  28503. }
  28504. return pickingInfo || new BABYLON.PickingInfo();
  28505. };
  28506. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28507. if (!BABYLON.PickingInfo) {
  28508. return null;
  28509. }
  28510. var pickingInfos = new Array();
  28511. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28512. var mesh = this.meshes[meshIndex];
  28513. if (predicate) {
  28514. if (!predicate(mesh)) {
  28515. continue;
  28516. }
  28517. }
  28518. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28519. continue;
  28520. }
  28521. var world = mesh.getWorldMatrix();
  28522. var ray = rayFunction(world);
  28523. var result = mesh.intersects(ray, false);
  28524. if (!result || !result.hit)
  28525. continue;
  28526. pickingInfos.push(result);
  28527. }
  28528. return pickingInfos;
  28529. };
  28530. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28531. if (!BABYLON.PickingInfo) {
  28532. return null;
  28533. }
  28534. var pickingInfo = null;
  28535. if (!camera) {
  28536. if (!this.activeCamera) {
  28537. return null;
  28538. }
  28539. camera = this.activeCamera;
  28540. }
  28541. if (this.spriteManagers.length > 0) {
  28542. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28543. var spriteManager = this.spriteManagers[spriteIndex];
  28544. if (!spriteManager.isPickable) {
  28545. continue;
  28546. }
  28547. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28548. if (!result || !result.hit)
  28549. continue;
  28550. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28551. continue;
  28552. pickingInfo = result;
  28553. if (fastCheck) {
  28554. break;
  28555. }
  28556. }
  28557. }
  28558. return pickingInfo || new BABYLON.PickingInfo();
  28559. };
  28560. /** Launch a ray to try to pick a mesh in the scene
  28561. * @param x position on screen
  28562. * @param y position on screen
  28563. * @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
  28564. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28565. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28566. * @returns a PickingInfo
  28567. */
  28568. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28569. var _this = this;
  28570. if (!BABYLON.PickingInfo) {
  28571. return null;
  28572. }
  28573. var result = this._internalPick(function (world) {
  28574. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28575. return _this._tempPickingRay;
  28576. }, predicate, fastCheck);
  28577. if (result) {
  28578. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28579. }
  28580. return result;
  28581. };
  28582. /** Launch a ray to try to pick a sprite in the scene
  28583. * @param x position on screen
  28584. * @param y position on screen
  28585. * @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
  28586. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28587. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28588. * @returns a PickingInfo
  28589. */
  28590. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28591. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28592. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28593. };
  28594. /** Use the given ray to pick a mesh in the scene
  28595. * @param ray The ray to use to pick meshes
  28596. * @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
  28597. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28598. * @returns a PickingInfo
  28599. */
  28600. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28601. var _this = this;
  28602. var result = this._internalPick(function (world) {
  28603. if (!_this._pickWithRayInverseMatrix) {
  28604. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28605. }
  28606. world.invertToRef(_this._pickWithRayInverseMatrix);
  28607. if (!_this._cachedRayForTransform) {
  28608. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28609. }
  28610. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28611. return _this._cachedRayForTransform;
  28612. }, predicate, fastCheck);
  28613. if (result) {
  28614. result.ray = ray;
  28615. }
  28616. return result;
  28617. };
  28618. /**
  28619. * Launch a ray to try to pick a mesh in the scene
  28620. * @param x X position on screen
  28621. * @param y Y position on screen
  28622. * @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
  28623. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28624. * @returns an array of PickingInfo
  28625. */
  28626. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28627. var _this = this;
  28628. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28629. };
  28630. /**
  28631. * Launch a ray to try to pick a mesh in the scene
  28632. * @param ray Ray to use
  28633. * @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
  28634. * @returns an array of PickingInfo
  28635. */
  28636. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28637. var _this = this;
  28638. return this._internalMultiPick(function (world) {
  28639. if (!_this._pickWithRayInverseMatrix) {
  28640. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28641. }
  28642. world.invertToRef(_this._pickWithRayInverseMatrix);
  28643. if (!_this._cachedRayForTransform) {
  28644. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28645. }
  28646. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28647. return _this._cachedRayForTransform;
  28648. }, predicate);
  28649. };
  28650. /**
  28651. * Force the value of meshUnderPointer
  28652. * @param mesh defines the mesh to use
  28653. */
  28654. Scene.prototype.setPointerOverMesh = function (mesh) {
  28655. if (this._pointerOverMesh === mesh) {
  28656. return;
  28657. }
  28658. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28659. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28660. }
  28661. this._pointerOverMesh = mesh;
  28662. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28663. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28664. }
  28665. };
  28666. /**
  28667. * Gets the mesh under the pointer
  28668. * @returns a Mesh or null if no mesh is under the pointer
  28669. */
  28670. Scene.prototype.getPointerOverMesh = function () {
  28671. return this._pointerOverMesh;
  28672. };
  28673. /**
  28674. * Force the sprite under the pointer
  28675. * @param sprite defines the sprite to use
  28676. */
  28677. Scene.prototype.setPointerOverSprite = function (sprite) {
  28678. if (this._pointerOverSprite === sprite) {
  28679. return;
  28680. }
  28681. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28682. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28683. }
  28684. this._pointerOverSprite = sprite;
  28685. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28686. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28687. }
  28688. };
  28689. /**
  28690. * Gets the sprite under the pointer
  28691. * @returns a Sprite or null if no sprite is under the pointer
  28692. */
  28693. Scene.prototype.getPointerOverSprite = function () {
  28694. return this._pointerOverSprite;
  28695. };
  28696. // Physics
  28697. /**
  28698. * Gets the current physics engine
  28699. * @returns a PhysicsEngine or null if none attached
  28700. */
  28701. Scene.prototype.getPhysicsEngine = function () {
  28702. return this._physicsEngine;
  28703. };
  28704. /**
  28705. * Enables physics to the current scene
  28706. * @param gravity defines the scene's gravity for the physics engine
  28707. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28708. * @return a boolean indicating if the physics engine was initialized
  28709. */
  28710. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28711. if (gravity === void 0) { gravity = null; }
  28712. if (this._physicsEngine) {
  28713. return true;
  28714. }
  28715. try {
  28716. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28717. return true;
  28718. }
  28719. catch (e) {
  28720. BABYLON.Tools.Error(e.message);
  28721. return false;
  28722. }
  28723. };
  28724. /**
  28725. * Disables and disposes the physics engine associated with the scene
  28726. */
  28727. Scene.prototype.disablePhysicsEngine = function () {
  28728. if (!this._physicsEngine) {
  28729. return;
  28730. }
  28731. this._physicsEngine.dispose();
  28732. this._physicsEngine = null;
  28733. };
  28734. /**
  28735. * Gets a boolean indicating if there is an active physics engine
  28736. * @returns a boolean indicating if there is an active physics engine
  28737. */
  28738. Scene.prototype.isPhysicsEnabled = function () {
  28739. return this._physicsEngine !== undefined;
  28740. };
  28741. /**
  28742. * Deletes a physics compound impostor
  28743. * @param compound defines the compound to delete
  28744. */
  28745. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28746. var mesh = compound.parts[0].mesh;
  28747. if (mesh.physicsImpostor) {
  28748. mesh.physicsImpostor.dispose( /*true*/);
  28749. mesh.physicsImpostor = null;
  28750. }
  28751. };
  28752. // Misc.
  28753. /** @hidden */
  28754. Scene.prototype._rebuildGeometries = function () {
  28755. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28756. var geometry = _a[_i];
  28757. geometry._rebuild();
  28758. }
  28759. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28760. var mesh = _c[_b];
  28761. mesh._rebuild();
  28762. }
  28763. if (this.postProcessManager) {
  28764. this.postProcessManager._rebuild();
  28765. }
  28766. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28767. var layer = _e[_d];
  28768. layer._rebuild();
  28769. }
  28770. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28771. var effectLayer = _g[_f];
  28772. effectLayer._rebuild();
  28773. }
  28774. if (this._boundingBoxRenderer) {
  28775. this._boundingBoxRenderer._rebuild();
  28776. }
  28777. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28778. var system = _j[_h];
  28779. system.rebuild();
  28780. }
  28781. if (this._postProcessRenderPipelineManager) {
  28782. this._postProcessRenderPipelineManager._rebuild();
  28783. }
  28784. };
  28785. /** @hidden */
  28786. Scene.prototype._rebuildTextures = function () {
  28787. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28788. var texture = _a[_i];
  28789. texture._rebuild();
  28790. }
  28791. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28792. };
  28793. /**
  28794. * Creates a default light for the scene.
  28795. * @param replace Whether to replace the existing lights in the scene.
  28796. */
  28797. Scene.prototype.createDefaultLight = function (replace) {
  28798. if (replace === void 0) { replace = false; }
  28799. // Dispose existing light in replace mode.
  28800. if (replace) {
  28801. if (this.lights) {
  28802. for (var i = 0; i < this.lights.length; i++) {
  28803. this.lights[i].dispose();
  28804. }
  28805. }
  28806. }
  28807. // Light
  28808. if (this.lights.length === 0) {
  28809. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28810. }
  28811. };
  28812. /**
  28813. * Creates a default camera for the scene.
  28814. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28815. * @param replace Whether to replace the existing active camera in the scene.
  28816. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28817. */
  28818. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28819. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28820. if (replace === void 0) { replace = false; }
  28821. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28822. // Dispose existing camera in replace mode.
  28823. if (replace) {
  28824. if (this.activeCamera) {
  28825. this.activeCamera.dispose();
  28826. this.activeCamera = null;
  28827. }
  28828. }
  28829. // Camera
  28830. if (!this.activeCamera) {
  28831. var worldExtends = this.getWorldExtends();
  28832. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28833. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28834. var camera;
  28835. var radius = worldSize.length() * 1.5;
  28836. // empty scene scenario!
  28837. if (!isFinite(radius)) {
  28838. radius = 1;
  28839. worldCenter.copyFromFloats(0, 0, 0);
  28840. }
  28841. if (createArcRotateCamera) {
  28842. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28843. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28844. arcRotateCamera.wheelPrecision = 100 / radius;
  28845. camera = arcRotateCamera;
  28846. }
  28847. else {
  28848. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28849. freeCamera.setTarget(worldCenter);
  28850. camera = freeCamera;
  28851. }
  28852. camera.minZ = radius * 0.01;
  28853. camera.maxZ = radius * 1000;
  28854. camera.speed = radius * 0.2;
  28855. this.activeCamera = camera;
  28856. var canvas = this.getEngine().getRenderingCanvas();
  28857. if (attachCameraControls && canvas) {
  28858. camera.attachControl(canvas);
  28859. }
  28860. }
  28861. };
  28862. /**
  28863. * Creates a default camera and a default light
  28864. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28865. * @param replace defines if the camera and/or light will replace the existing ones
  28866. * @param attachCameraControls defines if attachControl will be called on the new camera
  28867. */
  28868. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28869. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28870. if (replace === void 0) { replace = false; }
  28871. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28872. this.createDefaultLight(replace);
  28873. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28874. };
  28875. /**
  28876. * Creates a new sky box
  28877. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28878. * @param environmentTexture defines the texture to use as environment texture
  28879. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28880. * @param scale defines the overall scale of the skybox
  28881. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28882. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28883. * @returns a new mesh holding the sky box
  28884. */
  28885. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28886. if (pbr === void 0) { pbr = false; }
  28887. if (scale === void 0) { scale = 1000; }
  28888. if (blur === void 0) { blur = 0; }
  28889. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28890. if (!environmentTexture) {
  28891. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28892. return null;
  28893. }
  28894. if (setGlobalEnvTexture) {
  28895. if (environmentTexture) {
  28896. this.environmentTexture = environmentTexture;
  28897. }
  28898. }
  28899. // Skybox
  28900. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28901. if (pbr) {
  28902. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28903. hdrSkyboxMaterial.backFaceCulling = false;
  28904. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28905. if (hdrSkyboxMaterial.reflectionTexture) {
  28906. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28907. }
  28908. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28909. hdrSkyboxMaterial.disableLighting = true;
  28910. hdrSkyboxMaterial.twoSidedLighting = true;
  28911. hdrSkybox.infiniteDistance = true;
  28912. hdrSkybox.material = hdrSkyboxMaterial;
  28913. }
  28914. else {
  28915. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28916. skyboxMaterial.backFaceCulling = false;
  28917. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28918. if (skyboxMaterial.reflectionTexture) {
  28919. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28920. }
  28921. skyboxMaterial.disableLighting = true;
  28922. hdrSkybox.infiniteDistance = true;
  28923. hdrSkybox.material = skyboxMaterial;
  28924. }
  28925. return hdrSkybox;
  28926. };
  28927. /**
  28928. * Creates a new environment
  28929. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28930. * @param options defines the options you can use to configure the environment
  28931. * @returns the new EnvironmentHelper
  28932. */
  28933. Scene.prototype.createDefaultEnvironment = function (options) {
  28934. if (BABYLON.EnvironmentHelper) {
  28935. return new BABYLON.EnvironmentHelper(options, this);
  28936. }
  28937. return null;
  28938. };
  28939. /**
  28940. * Creates a new VREXperienceHelper
  28941. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28942. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28943. * @returns a new VREXperienceHelper
  28944. */
  28945. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28946. if (webVROptions === void 0) { webVROptions = {}; }
  28947. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28948. };
  28949. // Tags
  28950. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28951. if (tagsQuery === undefined) {
  28952. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28953. return list;
  28954. }
  28955. var listByTags = [];
  28956. forEach = forEach || (function (item) { return; });
  28957. for (var i in list) {
  28958. var item = list[i];
  28959. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28960. listByTags.push(item);
  28961. forEach(item);
  28962. }
  28963. }
  28964. return listByTags;
  28965. };
  28966. /**
  28967. * Get a list of meshes by tags
  28968. * @param tagsQuery defines the tags query to use
  28969. * @param forEach defines a predicate used to filter results
  28970. * @returns an array of Mesh
  28971. */
  28972. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28973. return this._getByTags(this.meshes, tagsQuery, forEach);
  28974. };
  28975. /**
  28976. * Get a list of cameras by tags
  28977. * @param tagsQuery defines the tags query to use
  28978. * @param forEach defines a predicate used to filter results
  28979. * @returns an array of Camera
  28980. */
  28981. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28982. return this._getByTags(this.cameras, tagsQuery, forEach);
  28983. };
  28984. /**
  28985. * Get a list of lights by tags
  28986. * @param tagsQuery defines the tags query to use
  28987. * @param forEach defines a predicate used to filter results
  28988. * @returns an array of Light
  28989. */
  28990. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28991. return this._getByTags(this.lights, tagsQuery, forEach);
  28992. };
  28993. /**
  28994. * Get a list of materials by tags
  28995. * @param tagsQuery defines the tags query to use
  28996. * @param forEach defines a predicate used to filter results
  28997. * @returns an array of Material
  28998. */
  28999. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29000. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29001. };
  29002. /**
  29003. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29004. * This allowed control for front to back rendering or reversly depending of the special needs.
  29005. *
  29006. * @param renderingGroupId The rendering group id corresponding to its index
  29007. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29008. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29009. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29010. */
  29011. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29012. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29013. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29014. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29015. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29016. };
  29017. /**
  29018. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29019. *
  29020. * @param renderingGroupId The rendering group id corresponding to its index
  29021. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29022. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29023. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29024. */
  29025. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29026. if (depth === void 0) { depth = true; }
  29027. if (stencil === void 0) { stencil = true; }
  29028. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29029. };
  29030. /**
  29031. * Will flag all materials as dirty to trigger new shader compilation
  29032. * @param flag defines the flag used to specify which material part must be marked as dirty
  29033. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29034. */
  29035. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29036. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29037. var material = _a[_i];
  29038. if (predicate && !predicate(material)) {
  29039. continue;
  29040. }
  29041. material.markAsDirty(flag);
  29042. }
  29043. };
  29044. /** @hidden */
  29045. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29046. var _this = this;
  29047. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29048. this._activeRequests.push(request);
  29049. request.onCompleteObservable.add(function (request) {
  29050. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29051. });
  29052. return request;
  29053. };
  29054. /** @hidden */
  29055. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29056. var _this = this;
  29057. return new Promise(function (resolve, reject) {
  29058. _this._loadFile(url, function (data) {
  29059. resolve(data);
  29060. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29061. reject(exception);
  29062. });
  29063. });
  29064. };
  29065. // Statics
  29066. Scene._FOGMODE_NONE = 0;
  29067. Scene._FOGMODE_EXP = 1;
  29068. Scene._FOGMODE_EXP2 = 2;
  29069. Scene._FOGMODE_LINEAR = 3;
  29070. Scene._uniqueIdCounter = 0;
  29071. /**
  29072. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29073. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29074. */
  29075. Scene.MinDeltaTime = 1.0;
  29076. /**
  29077. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29078. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29079. */
  29080. Scene.MaxDeltaTime = 1000.0;
  29081. /** The distance in pixel that you have to move to prevent some events */
  29082. Scene.DragMovementThreshold = 10; // in pixels
  29083. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29084. Scene.LongPressDelay = 500; // in milliseconds
  29085. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29086. Scene.DoubleClickDelay = 300; // in milliseconds
  29087. /** If you need to check double click without raising a single click at first click, enable this flag */
  29088. Scene.ExclusiveDoubleClickMode = false;
  29089. return Scene;
  29090. }());
  29091. BABYLON.Scene = Scene;
  29092. })(BABYLON || (BABYLON = {}));
  29093. //# sourceMappingURL=babylon.scene.js.map
  29094. var BABYLON;
  29095. (function (BABYLON) {
  29096. /**
  29097. * Set of assets to keep when moving a scene into an asset container.
  29098. */
  29099. var KeepAssets = /** @class */ (function () {
  29100. function KeepAssets() {
  29101. /**
  29102. * Cameras to keep.
  29103. */
  29104. this.cameras = new Array();
  29105. /**
  29106. * Lights to keep.
  29107. */
  29108. this.lights = new Array();
  29109. /**
  29110. * Meshes to keep.
  29111. */
  29112. this.meshes = new Array();
  29113. /**
  29114. * Skeletons to keep.
  29115. */
  29116. this.skeletons = new Array();
  29117. /**
  29118. * ParticleSystems to keep.
  29119. */
  29120. this.particleSystems = new Array();
  29121. /**
  29122. * Animations to keep.
  29123. */
  29124. this.animations = new Array();
  29125. /**
  29126. * AnimationGroups to keep.
  29127. */
  29128. this.animationGroups = new Array();
  29129. /**
  29130. * MultiMaterials to keep.
  29131. */
  29132. this.multiMaterials = new Array();
  29133. /**
  29134. * Materials to keep.
  29135. */
  29136. this.materials = new Array();
  29137. /**
  29138. * MorphTargetManagers to keep.
  29139. */
  29140. this.morphTargetManagers = new Array();
  29141. /**
  29142. * Geometries to keep.
  29143. */
  29144. this.geometries = new Array();
  29145. /**
  29146. * TransformNodes to keep.
  29147. */
  29148. this.transformNodes = new Array();
  29149. /**
  29150. * LensFlareSystems to keep.
  29151. */
  29152. this.lensFlareSystems = new Array();
  29153. /**
  29154. * ShadowGenerators to keep.
  29155. */
  29156. this.shadowGenerators = new Array();
  29157. /**
  29158. * ActionManagers to keep.
  29159. */
  29160. this.actionManagers = new Array();
  29161. /**
  29162. * Sounds to keep.
  29163. */
  29164. this.sounds = new Array();
  29165. /**
  29166. * Textures to keep.
  29167. */
  29168. this.textures = new Array();
  29169. /**
  29170. * Effect layers to keep.
  29171. */
  29172. this.effectLayers = new Array();
  29173. }
  29174. return KeepAssets;
  29175. }());
  29176. BABYLON.KeepAssets = KeepAssets;
  29177. /**
  29178. * Container with a set of assets that can be added or removed from a scene.
  29179. */
  29180. var AssetContainer = /** @class */ (function () {
  29181. /**
  29182. * Instantiates an AssetContainer.
  29183. * @param scene The scene the AssetContainer belongs to.
  29184. */
  29185. function AssetContainer(scene) {
  29186. // Objects
  29187. /**
  29188. * Cameras populated in the container.
  29189. */
  29190. this.cameras = new Array();
  29191. /**
  29192. * Lights populated in the container.
  29193. */
  29194. this.lights = new Array();
  29195. /**
  29196. * Meshes populated in the container.
  29197. */
  29198. this.meshes = new Array();
  29199. /**
  29200. * Skeletons populated in the container.
  29201. */
  29202. this.skeletons = new Array();
  29203. /**
  29204. * ParticleSystems populated in the container.
  29205. */
  29206. this.particleSystems = new Array();
  29207. /**
  29208. * Animations populated in the container.
  29209. */
  29210. this.animations = new Array();
  29211. /**
  29212. * AnimationGroups populated in the container.
  29213. */
  29214. this.animationGroups = new Array();
  29215. /**
  29216. * MultiMaterials populated in the container.
  29217. */
  29218. this.multiMaterials = new Array();
  29219. /**
  29220. * Materials populated in the container.
  29221. */
  29222. this.materials = new Array();
  29223. /**
  29224. * MorphTargetManagers populated in the container.
  29225. */
  29226. this.morphTargetManagers = new Array();
  29227. /**
  29228. * Geometries populated in the container.
  29229. */
  29230. this.geometries = new Array();
  29231. /**
  29232. * TransformNodes populated in the container.
  29233. */
  29234. this.transformNodes = new Array();
  29235. /**
  29236. * LensFlareSystems populated in the container.
  29237. */
  29238. this.lensFlareSystems = new Array();
  29239. /**
  29240. * ShadowGenerators populated in the container.
  29241. */
  29242. this.shadowGenerators = new Array();
  29243. /**
  29244. * ActionManagers populated in the container.
  29245. */
  29246. this.actionManagers = new Array();
  29247. /**
  29248. * Sounds populated in the container.
  29249. */
  29250. this.sounds = new Array();
  29251. /**
  29252. * Textures populated in the container.
  29253. */
  29254. this.textures = new Array();
  29255. /**
  29256. * Effect layers populated in the container.
  29257. */
  29258. this.effectLayers = new Array();
  29259. this.scene = scene;
  29260. }
  29261. /**
  29262. * Adds all the assets from the container to the scene.
  29263. */
  29264. AssetContainer.prototype.addAllToScene = function () {
  29265. var _this = this;
  29266. this.cameras.forEach(function (o) {
  29267. _this.scene.addCamera(o);
  29268. });
  29269. this.lights.forEach(function (o) {
  29270. _this.scene.addLight(o);
  29271. });
  29272. this.meshes.forEach(function (o) {
  29273. _this.scene.addMesh(o);
  29274. });
  29275. this.skeletons.forEach(function (o) {
  29276. _this.scene.addSkeleton(o);
  29277. });
  29278. this.particleSystems.forEach(function (o) {
  29279. _this.scene.addParticleSystem(o);
  29280. });
  29281. this.animations.forEach(function (o) {
  29282. _this.scene.addAnimation(o);
  29283. });
  29284. this.animationGroups.forEach(function (o) {
  29285. _this.scene.addAnimationGroup(o);
  29286. });
  29287. this.multiMaterials.forEach(function (o) {
  29288. _this.scene.addMultiMaterial(o);
  29289. });
  29290. this.materials.forEach(function (o) {
  29291. _this.scene.addMaterial(o);
  29292. });
  29293. this.morphTargetManagers.forEach(function (o) {
  29294. _this.scene.addMorphTargetManager(o);
  29295. });
  29296. this.geometries.forEach(function (o) {
  29297. _this.scene.addGeometry(o);
  29298. });
  29299. this.transformNodes.forEach(function (o) {
  29300. _this.scene.addTransformNode(o);
  29301. });
  29302. this.lensFlareSystems.forEach(function (o) {
  29303. _this.scene.addLensFlareSystem(o);
  29304. });
  29305. this.actionManagers.forEach(function (o) {
  29306. _this.scene.addActionManager(o);
  29307. });
  29308. this.sounds.forEach(function (o) {
  29309. o.play();
  29310. o.autoplay = true;
  29311. _this.scene.mainSoundTrack.AddSound(o);
  29312. });
  29313. this.textures.forEach(function (o) {
  29314. _this.scene.addTexture(o);
  29315. });
  29316. this.effectLayers.forEach(function (o) {
  29317. _this.scene.addEffectLayer(o);
  29318. });
  29319. };
  29320. /**
  29321. * Removes all the assets in the container from the scene
  29322. */
  29323. AssetContainer.prototype.removeAllFromScene = function () {
  29324. var _this = this;
  29325. this.cameras.forEach(function (o) {
  29326. _this.scene.removeCamera(o);
  29327. });
  29328. this.lights.forEach(function (o) {
  29329. _this.scene.removeLight(o);
  29330. });
  29331. this.meshes.forEach(function (o) {
  29332. _this.scene.removeMesh(o);
  29333. });
  29334. this.skeletons.forEach(function (o) {
  29335. _this.scene.removeSkeleton(o);
  29336. });
  29337. this.particleSystems.forEach(function (o) {
  29338. _this.scene.removeParticleSystem(o);
  29339. });
  29340. this.animations.forEach(function (o) {
  29341. _this.scene.removeAnimation(o);
  29342. });
  29343. this.animationGroups.forEach(function (o) {
  29344. _this.scene.removeAnimationGroup(o);
  29345. });
  29346. this.multiMaterials.forEach(function (o) {
  29347. _this.scene.removeMultiMaterial(o);
  29348. });
  29349. this.materials.forEach(function (o) {
  29350. _this.scene.removeMaterial(o);
  29351. });
  29352. this.morphTargetManagers.forEach(function (o) {
  29353. _this.scene.removeMorphTargetManager(o);
  29354. });
  29355. this.geometries.forEach(function (o) {
  29356. _this.scene.removeGeometry(o);
  29357. });
  29358. this.transformNodes.forEach(function (o) {
  29359. _this.scene.removeTransformNode(o);
  29360. });
  29361. this.lensFlareSystems.forEach(function (o) {
  29362. _this.scene.removeLensFlareSystem(o);
  29363. });
  29364. this.actionManagers.forEach(function (o) {
  29365. _this.scene.removeActionManager(o);
  29366. });
  29367. this.sounds.forEach(function (o) {
  29368. o.stop();
  29369. o.autoplay = false;
  29370. _this.scene.mainSoundTrack.RemoveSound(o);
  29371. });
  29372. this.textures.forEach(function (o) {
  29373. _this.scene.removeTexture(o);
  29374. });
  29375. this.effectLayers.forEach(function (o) {
  29376. _this.scene.removeEffectLayer(o);
  29377. });
  29378. };
  29379. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29380. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29381. var asset = sourceAssets_1[_i];
  29382. var move = true;
  29383. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29384. var keepAsset = keepAssets_1[_a];
  29385. if (asset === keepAsset) {
  29386. move = false;
  29387. break;
  29388. }
  29389. }
  29390. if (move) {
  29391. targetAssets.push(asset);
  29392. }
  29393. }
  29394. };
  29395. /**
  29396. * Removes all the assets contained in the scene and adds them to the container.
  29397. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29398. */
  29399. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29400. if (keepAssets === undefined) {
  29401. keepAssets = new KeepAssets();
  29402. }
  29403. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29404. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29405. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29406. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29407. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29408. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29409. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29410. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29411. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29412. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29413. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29414. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29415. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29416. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29417. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29418. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29419. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29420. this.removeAllFromScene();
  29421. };
  29422. /**
  29423. * 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.
  29424. * @returns the root mesh
  29425. */
  29426. AssetContainer.prototype.createRootMesh = function () {
  29427. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29428. this.meshes.forEach(function (m) {
  29429. if (!m.parent) {
  29430. rootMesh.addChild(m);
  29431. }
  29432. });
  29433. this.meshes.unshift(rootMesh);
  29434. return rootMesh;
  29435. };
  29436. return AssetContainer;
  29437. }());
  29438. BABYLON.AssetContainer = AssetContainer;
  29439. })(BABYLON || (BABYLON = {}));
  29440. //# sourceMappingURL=babylon.assetContainer.js.map
  29441. var BABYLON;
  29442. (function (BABYLON) {
  29443. var Buffer = /** @class */ (function () {
  29444. /**
  29445. * Constructor
  29446. * @param engine the engine
  29447. * @param data the data to use for this buffer
  29448. * @param updatable whether the data is updatable
  29449. * @param stride the stride (optional)
  29450. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29451. * @param instanced whether the buffer is instanced (optional)
  29452. * @param useBytes set to true if the stride in in bytes (optional)
  29453. */
  29454. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29455. if (stride === void 0) { stride = 0; }
  29456. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29457. if (instanced === void 0) { instanced = false; }
  29458. if (useBytes === void 0) { useBytes = false; }
  29459. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29460. this._engine = engine.getScene().getEngine();
  29461. }
  29462. else {
  29463. this._engine = engine;
  29464. }
  29465. this._updatable = updatable;
  29466. this._instanced = instanced;
  29467. this._data = data;
  29468. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29469. if (!postponeInternalCreation) { // by default
  29470. this.create();
  29471. }
  29472. }
  29473. /**
  29474. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29475. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29476. * @param offset defines offset in the buffer (0 by default)
  29477. * @param size defines the size in floats of attributes (position is 3 for instance)
  29478. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29479. * @param instanced defines if the vertex buffer contains indexed data
  29480. * @param useBytes defines if the offset and stride are in bytes
  29481. * @returns the new vertex buffer
  29482. */
  29483. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29484. if (useBytes === void 0) { useBytes = false; }
  29485. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29486. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29487. // a lot of these parameters are ignored as they are overriden by the buffer
  29488. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29489. };
  29490. // Properties
  29491. Buffer.prototype.isUpdatable = function () {
  29492. return this._updatable;
  29493. };
  29494. Buffer.prototype.getData = function () {
  29495. return this._data;
  29496. };
  29497. Buffer.prototype.getBuffer = function () {
  29498. return this._buffer;
  29499. };
  29500. /**
  29501. * Gets the stride in float32 units (i.e. byte stride / 4).
  29502. * May not be an integer if the byte stride is not divisible by 4.
  29503. * DEPRECATED. Use byteStride instead.
  29504. * @returns the stride in float32 units
  29505. */
  29506. Buffer.prototype.getStrideSize = function () {
  29507. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29508. };
  29509. // Methods
  29510. Buffer.prototype.create = function (data) {
  29511. if (data === void 0) { data = null; }
  29512. if (!data && this._buffer) {
  29513. return; // nothing to do
  29514. }
  29515. data = data || this._data;
  29516. if (!data) {
  29517. return;
  29518. }
  29519. if (!this._buffer) { // create buffer
  29520. if (this._updatable) {
  29521. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29522. this._data = data;
  29523. }
  29524. else {
  29525. this._buffer = this._engine.createVertexBuffer(data);
  29526. }
  29527. }
  29528. else if (this._updatable) { // update buffer
  29529. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29530. this._data = data;
  29531. }
  29532. };
  29533. Buffer.prototype._rebuild = function () {
  29534. this._buffer = null;
  29535. this.create(this._data);
  29536. };
  29537. Buffer.prototype.update = function (data) {
  29538. this.create(data);
  29539. };
  29540. /**
  29541. * Updates the data directly.
  29542. * @param data the new data
  29543. * @param offset the new offset
  29544. * @param vertexCount the vertex count (optional)
  29545. * @param useBytes set to true if the offset is in bytes
  29546. */
  29547. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29548. if (useBytes === void 0) { useBytes = false; }
  29549. if (!this._buffer) {
  29550. return;
  29551. }
  29552. if (this._updatable) { // update buffer
  29553. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29554. this._data = null;
  29555. }
  29556. };
  29557. Buffer.prototype.dispose = function () {
  29558. if (!this._buffer) {
  29559. return;
  29560. }
  29561. if (this._engine._releaseBuffer(this._buffer)) {
  29562. this._buffer = null;
  29563. }
  29564. };
  29565. return Buffer;
  29566. }());
  29567. BABYLON.Buffer = Buffer;
  29568. })(BABYLON || (BABYLON = {}));
  29569. //# sourceMappingURL=babylon.buffer.js.map
  29570. var BABYLON;
  29571. (function (BABYLON) {
  29572. var VertexBuffer = /** @class */ (function () {
  29573. /**
  29574. * Constructor
  29575. * @param engine the engine
  29576. * @param data the data to use for this vertex buffer
  29577. * @param kind the vertex buffer kind
  29578. * @param updatable whether the data is updatable
  29579. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29580. * @param stride the stride (optional)
  29581. * @param instanced whether the buffer is instanced (optional)
  29582. * @param offset the offset of the data (optional)
  29583. * @param size the number of components (optional)
  29584. * @param type the type of the component (optional)
  29585. * @param normalized whether the data contains normalized data (optional)
  29586. * @param useBytes set to true if stride and offset are in bytes (optional)
  29587. */
  29588. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29589. if (normalized === void 0) { normalized = false; }
  29590. if (useBytes === void 0) { useBytes = false; }
  29591. if (data instanceof BABYLON.Buffer) {
  29592. this._buffer = data;
  29593. this._ownsBuffer = false;
  29594. }
  29595. else {
  29596. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29597. this._ownsBuffer = true;
  29598. }
  29599. this._kind = kind;
  29600. if (type == undefined) {
  29601. var data_1 = this.getData();
  29602. this.type = VertexBuffer.FLOAT;
  29603. if (data_1 instanceof Int8Array)
  29604. this.type = VertexBuffer.BYTE;
  29605. else if (data_1 instanceof Uint8Array)
  29606. this.type = VertexBuffer.UNSIGNED_BYTE;
  29607. else if (data_1 instanceof Int16Array)
  29608. this.type = VertexBuffer.SHORT;
  29609. else if (data_1 instanceof Uint16Array)
  29610. this.type = VertexBuffer.UNSIGNED_SHORT;
  29611. else if (data_1 instanceof Int32Array)
  29612. this.type = VertexBuffer.INT;
  29613. else if (data_1 instanceof Uint32Array)
  29614. this.type = VertexBuffer.UNSIGNED_INT;
  29615. }
  29616. else {
  29617. this.type = type;
  29618. }
  29619. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29620. if (useBytes) {
  29621. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29622. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29623. this.byteOffset = offset || 0;
  29624. }
  29625. else {
  29626. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29627. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29628. this.byteOffset = (offset || 0) * typeByteLength;
  29629. }
  29630. this.normalized = normalized;
  29631. this._instanced = instanced !== undefined ? instanced : false;
  29632. this._instanceDivisor = instanced ? 1 : 0;
  29633. }
  29634. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29635. /**
  29636. * Gets or sets the instance divisor when in instanced mode
  29637. */
  29638. get: function () {
  29639. return this._instanceDivisor;
  29640. },
  29641. set: function (value) {
  29642. this._instanceDivisor = value;
  29643. if (value == 0) {
  29644. this._instanced = false;
  29645. }
  29646. else {
  29647. this._instanced = true;
  29648. }
  29649. },
  29650. enumerable: true,
  29651. configurable: true
  29652. });
  29653. VertexBuffer.prototype._rebuild = function () {
  29654. if (!this._buffer) {
  29655. return;
  29656. }
  29657. this._buffer._rebuild();
  29658. };
  29659. /**
  29660. * Returns the kind of the VertexBuffer (string).
  29661. */
  29662. VertexBuffer.prototype.getKind = function () {
  29663. return this._kind;
  29664. };
  29665. // Properties
  29666. /**
  29667. * Boolean : is the VertexBuffer updatable ?
  29668. */
  29669. VertexBuffer.prototype.isUpdatable = function () {
  29670. return this._buffer.isUpdatable();
  29671. };
  29672. /**
  29673. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29674. */
  29675. VertexBuffer.prototype.getData = function () {
  29676. return this._buffer.getData();
  29677. };
  29678. /**
  29679. * Returns the WebGLBuffer associated to the VertexBuffer.
  29680. */
  29681. VertexBuffer.prototype.getBuffer = function () {
  29682. return this._buffer.getBuffer();
  29683. };
  29684. /**
  29685. * Returns the stride as a multiple of the type byte length.
  29686. * DEPRECATED. Use byteStride instead.
  29687. */
  29688. VertexBuffer.prototype.getStrideSize = function () {
  29689. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29690. };
  29691. /**
  29692. * Returns the offset as a multiple of the type byte length.
  29693. * DEPRECATED. Use byteOffset instead.
  29694. */
  29695. VertexBuffer.prototype.getOffset = function () {
  29696. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29697. };
  29698. /**
  29699. * Returns the number of components per vertex attribute (integer).
  29700. */
  29701. VertexBuffer.prototype.getSize = function () {
  29702. return this._size;
  29703. };
  29704. /**
  29705. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29706. */
  29707. VertexBuffer.prototype.getIsInstanced = function () {
  29708. return this._instanced;
  29709. };
  29710. /**
  29711. * Returns the instancing divisor, zero for non-instanced (integer).
  29712. */
  29713. VertexBuffer.prototype.getInstanceDivisor = function () {
  29714. return this._instanceDivisor;
  29715. };
  29716. // Methods
  29717. /**
  29718. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29719. * Returns the created WebGLBuffer.
  29720. */
  29721. VertexBuffer.prototype.create = function (data) {
  29722. return this._buffer.create(data);
  29723. };
  29724. /**
  29725. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29726. * This function will create a new buffer if the current one is not updatable
  29727. * Returns the updated WebGLBuffer.
  29728. */
  29729. VertexBuffer.prototype.update = function (data) {
  29730. return this._buffer.update(data);
  29731. };
  29732. /**
  29733. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29734. * Returns the directly updated WebGLBuffer.
  29735. * @param data the new data
  29736. * @param offset the new offset
  29737. * @param useBytes set to true if the offset is in bytes
  29738. */
  29739. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29740. if (useBytes === void 0) { useBytes = false; }
  29741. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29742. };
  29743. /**
  29744. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29745. */
  29746. VertexBuffer.prototype.dispose = function () {
  29747. if (this._ownsBuffer) {
  29748. this._buffer.dispose();
  29749. }
  29750. };
  29751. /**
  29752. * Enumerates each value of this vertex buffer as numbers.
  29753. * @param count the number of values to enumerate
  29754. * @param callback the callback function called for each value
  29755. */
  29756. VertexBuffer.prototype.forEach = function (count, callback) {
  29757. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29758. };
  29759. Object.defineProperty(VertexBuffer, "PositionKind", {
  29760. get: function () {
  29761. return VertexBuffer._PositionKind;
  29762. },
  29763. enumerable: true,
  29764. configurable: true
  29765. });
  29766. Object.defineProperty(VertexBuffer, "NormalKind", {
  29767. get: function () {
  29768. return VertexBuffer._NormalKind;
  29769. },
  29770. enumerable: true,
  29771. configurable: true
  29772. });
  29773. Object.defineProperty(VertexBuffer, "TangentKind", {
  29774. get: function () {
  29775. return VertexBuffer._TangentKind;
  29776. },
  29777. enumerable: true,
  29778. configurable: true
  29779. });
  29780. Object.defineProperty(VertexBuffer, "UVKind", {
  29781. get: function () {
  29782. return VertexBuffer._UVKind;
  29783. },
  29784. enumerable: true,
  29785. configurable: true
  29786. });
  29787. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29788. get: function () {
  29789. return VertexBuffer._UV2Kind;
  29790. },
  29791. enumerable: true,
  29792. configurable: true
  29793. });
  29794. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29795. get: function () {
  29796. return VertexBuffer._UV3Kind;
  29797. },
  29798. enumerable: true,
  29799. configurable: true
  29800. });
  29801. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29802. get: function () {
  29803. return VertexBuffer._UV4Kind;
  29804. },
  29805. enumerable: true,
  29806. configurable: true
  29807. });
  29808. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29809. get: function () {
  29810. return VertexBuffer._UV5Kind;
  29811. },
  29812. enumerable: true,
  29813. configurable: true
  29814. });
  29815. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29816. get: function () {
  29817. return VertexBuffer._UV6Kind;
  29818. },
  29819. enumerable: true,
  29820. configurable: true
  29821. });
  29822. Object.defineProperty(VertexBuffer, "ColorKind", {
  29823. get: function () {
  29824. return VertexBuffer._ColorKind;
  29825. },
  29826. enumerable: true,
  29827. configurable: true
  29828. });
  29829. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29830. get: function () {
  29831. return VertexBuffer._MatricesIndicesKind;
  29832. },
  29833. enumerable: true,
  29834. configurable: true
  29835. });
  29836. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29837. get: function () {
  29838. return VertexBuffer._MatricesWeightsKind;
  29839. },
  29840. enumerable: true,
  29841. configurable: true
  29842. });
  29843. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29844. get: function () {
  29845. return VertexBuffer._MatricesIndicesExtraKind;
  29846. },
  29847. enumerable: true,
  29848. configurable: true
  29849. });
  29850. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29851. get: function () {
  29852. return VertexBuffer._MatricesWeightsExtraKind;
  29853. },
  29854. enumerable: true,
  29855. configurable: true
  29856. });
  29857. /**
  29858. * Deduces the stride given a kind.
  29859. * @param kind The kind string to deduce
  29860. * @returns The deduced stride
  29861. */
  29862. VertexBuffer.DeduceStride = function (kind) {
  29863. switch (kind) {
  29864. case VertexBuffer.UVKind:
  29865. case VertexBuffer.UV2Kind:
  29866. case VertexBuffer.UV3Kind:
  29867. case VertexBuffer.UV4Kind:
  29868. case VertexBuffer.UV5Kind:
  29869. case VertexBuffer.UV6Kind:
  29870. return 2;
  29871. case VertexBuffer.NormalKind:
  29872. case VertexBuffer.PositionKind:
  29873. return 3;
  29874. case VertexBuffer.ColorKind:
  29875. case VertexBuffer.MatricesIndicesKind:
  29876. case VertexBuffer.MatricesIndicesExtraKind:
  29877. case VertexBuffer.MatricesWeightsKind:
  29878. case VertexBuffer.MatricesWeightsExtraKind:
  29879. case VertexBuffer.TangentKind:
  29880. return 4;
  29881. default:
  29882. throw new Error("Invalid kind '" + kind + "'");
  29883. }
  29884. };
  29885. /**
  29886. * Gets the byte length of the given type.
  29887. * @param type the type
  29888. * @returns the number of bytes
  29889. */
  29890. VertexBuffer.GetTypeByteLength = function (type) {
  29891. switch (type) {
  29892. case VertexBuffer.BYTE:
  29893. case VertexBuffer.UNSIGNED_BYTE:
  29894. return 1;
  29895. case VertexBuffer.SHORT:
  29896. case VertexBuffer.UNSIGNED_SHORT:
  29897. return 2;
  29898. case VertexBuffer.INT:
  29899. case VertexBuffer.FLOAT:
  29900. return 4;
  29901. default:
  29902. throw new Error("Invalid type '" + type + "'");
  29903. }
  29904. };
  29905. /**
  29906. * Enumerates each value of the given parameters as numbers.
  29907. * @param data the data to enumerate
  29908. * @param byteOffset the byte offset of the data
  29909. * @param byteStride the byte stride of the data
  29910. * @param componentCount the number of components per element
  29911. * @param componentType the type of the component
  29912. * @param count the total number of components
  29913. * @param normalized whether the data is normalized
  29914. * @param callback the callback function called for each value
  29915. */
  29916. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29917. if (data instanceof Array) {
  29918. var offset = byteOffset / 4;
  29919. var stride = byteStride / 4;
  29920. for (var index = 0; index < count; index += componentCount) {
  29921. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29922. callback(data[offset + componentIndex], index + componentIndex);
  29923. }
  29924. offset += stride;
  29925. }
  29926. }
  29927. else {
  29928. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29929. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29930. for (var index = 0; index < count; index += componentCount) {
  29931. var componentByteOffset = byteOffset;
  29932. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29933. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29934. callback(value, index + componentIndex);
  29935. componentByteOffset += componentByteLength;
  29936. }
  29937. byteOffset += byteStride;
  29938. }
  29939. }
  29940. };
  29941. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29942. switch (type) {
  29943. case VertexBuffer.BYTE: {
  29944. var value = dataView.getInt8(byteOffset);
  29945. if (normalized) {
  29946. value = Math.max(value / 127, -1);
  29947. }
  29948. return value;
  29949. }
  29950. case VertexBuffer.UNSIGNED_BYTE: {
  29951. var value = dataView.getUint8(byteOffset);
  29952. if (normalized) {
  29953. value = value / 255;
  29954. }
  29955. return value;
  29956. }
  29957. case VertexBuffer.SHORT: {
  29958. var value = dataView.getInt16(byteOffset, true);
  29959. if (normalized) {
  29960. value = Math.max(value / 16383, -1);
  29961. }
  29962. return value;
  29963. }
  29964. case VertexBuffer.UNSIGNED_SHORT: {
  29965. var value = dataView.getUint16(byteOffset, true);
  29966. if (normalized) {
  29967. value = value / 65535;
  29968. }
  29969. return value;
  29970. }
  29971. case VertexBuffer.FLOAT: {
  29972. return dataView.getFloat32(byteOffset, true);
  29973. }
  29974. default: {
  29975. throw new Error("Invalid component type " + type);
  29976. }
  29977. }
  29978. };
  29979. /**
  29980. * The byte type.
  29981. */
  29982. VertexBuffer.BYTE = 5120;
  29983. /**
  29984. * The unsigned byte type.
  29985. */
  29986. VertexBuffer.UNSIGNED_BYTE = 5121;
  29987. /**
  29988. * The short type.
  29989. */
  29990. VertexBuffer.SHORT = 5122;
  29991. /**
  29992. * The unsigned short type.
  29993. */
  29994. VertexBuffer.UNSIGNED_SHORT = 5123;
  29995. /**
  29996. * The integer type.
  29997. */
  29998. VertexBuffer.INT = 5124;
  29999. /**
  30000. * The unsigned integer type.
  30001. */
  30002. VertexBuffer.UNSIGNED_INT = 5125;
  30003. /**
  30004. * The float type.
  30005. */
  30006. VertexBuffer.FLOAT = 5126;
  30007. // Enums
  30008. VertexBuffer._PositionKind = "position";
  30009. VertexBuffer._NormalKind = "normal";
  30010. VertexBuffer._TangentKind = "tangent";
  30011. VertexBuffer._UVKind = "uv";
  30012. VertexBuffer._UV2Kind = "uv2";
  30013. VertexBuffer._UV3Kind = "uv3";
  30014. VertexBuffer._UV4Kind = "uv4";
  30015. VertexBuffer._UV5Kind = "uv5";
  30016. VertexBuffer._UV6Kind = "uv6";
  30017. VertexBuffer._ColorKind = "color";
  30018. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30019. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30020. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30021. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30022. return VertexBuffer;
  30023. }());
  30024. BABYLON.VertexBuffer = VertexBuffer;
  30025. })(BABYLON || (BABYLON = {}));
  30026. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30027. var BABYLON;
  30028. (function (BABYLON) {
  30029. /**
  30030. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30031. */
  30032. var DummyInternalTextureTracker = /** @class */ (function () {
  30033. function DummyInternalTextureTracker() {
  30034. /**
  30035. * Gets or set the previous tracker in the list
  30036. */
  30037. this.previous = null;
  30038. /**
  30039. * Gets or set the next tracker in the list
  30040. */
  30041. this.next = null;
  30042. }
  30043. return DummyInternalTextureTracker;
  30044. }());
  30045. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30046. })(BABYLON || (BABYLON = {}));
  30047. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30048. var BABYLON;
  30049. (function (BABYLON) {
  30050. /**
  30051. * Class used to store data associated with WebGL texture data for the engine
  30052. * This class should not be used directly
  30053. */
  30054. var InternalTexture = /** @class */ (function () {
  30055. /**
  30056. * Creates a new InternalTexture
  30057. * @param engine defines the engine to use
  30058. * @param dataSource defines the type of data that will be used
  30059. */
  30060. function InternalTexture(engine, dataSource) {
  30061. /**
  30062. * Observable called when the texture is loaded
  30063. */
  30064. this.onLoadedObservable = new BABYLON.Observable();
  30065. /**
  30066. * Gets or set the previous tracker in the list
  30067. */
  30068. this.previous = null;
  30069. /**
  30070. * Gets or set the next tracker in the list
  30071. */
  30072. this.next = null;
  30073. // Private
  30074. /** @hidden */
  30075. this._initialSlot = -1;
  30076. /** @hidden */
  30077. this._designatedSlot = -1;
  30078. /** @hidden */
  30079. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30080. /** @hidden */
  30081. this._comparisonFunction = 0;
  30082. /** @hidden */
  30083. this._isRGBD = false;
  30084. /** @hidden */
  30085. this._references = 1;
  30086. this._engine = engine;
  30087. this._dataSource = dataSource;
  30088. this._webGLTexture = engine._createTexture();
  30089. }
  30090. /**
  30091. * Gets the Engine the texture belongs to.
  30092. * @returns The babylon engine
  30093. */
  30094. InternalTexture.prototype.getEngine = function () {
  30095. return this._engine;
  30096. };
  30097. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30098. /**
  30099. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30100. */
  30101. get: function () {
  30102. return this._dataSource;
  30103. },
  30104. enumerable: true,
  30105. configurable: true
  30106. });
  30107. /**
  30108. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30109. */
  30110. InternalTexture.prototype.incrementReferences = function () {
  30111. this._references++;
  30112. };
  30113. /**
  30114. * Change the size of the texture (not the size of the content)
  30115. * @param width defines the new width
  30116. * @param height defines the new height
  30117. * @param depth defines the new depth (1 by default)
  30118. */
  30119. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30120. if (depth === void 0) { depth = 1; }
  30121. this.width = width;
  30122. this.height = height;
  30123. this.depth = depth;
  30124. this.baseWidth = width;
  30125. this.baseHeight = height;
  30126. this.baseDepth = depth;
  30127. this._size = width * height * depth;
  30128. };
  30129. /** @hidden */
  30130. InternalTexture.prototype._rebuild = function () {
  30131. var _this = this;
  30132. var proxy;
  30133. this.isReady = false;
  30134. this._cachedCoordinatesMode = null;
  30135. this._cachedWrapU = null;
  30136. this._cachedWrapV = null;
  30137. this._cachedAnisotropicFilteringLevel = null;
  30138. switch (this._dataSource) {
  30139. case InternalTexture.DATASOURCE_TEMP:
  30140. return;
  30141. case InternalTexture.DATASOURCE_URL:
  30142. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30143. _this.isReady = true;
  30144. }, null, this._buffer, undefined, this.format);
  30145. proxy._swapAndDie(this);
  30146. return;
  30147. case InternalTexture.DATASOURCE_RAW:
  30148. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30149. proxy._swapAndDie(this);
  30150. this.isReady = true;
  30151. return;
  30152. case InternalTexture.DATASOURCE_RAW3D:
  30153. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30154. proxy._swapAndDie(this);
  30155. this.isReady = true;
  30156. return;
  30157. case InternalTexture.DATASOURCE_DYNAMIC:
  30158. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30159. proxy._swapAndDie(this);
  30160. // The engine will make sure to update content so no need to flag it as isReady = true
  30161. return;
  30162. case InternalTexture.DATASOURCE_RENDERTARGET:
  30163. var options = new BABYLON.RenderTargetCreationOptions();
  30164. options.generateDepthBuffer = this._generateDepthBuffer;
  30165. options.generateMipMaps = this.generateMipMaps;
  30166. options.generateStencilBuffer = this._generateStencilBuffer;
  30167. options.samplingMode = this.samplingMode;
  30168. options.type = this.type;
  30169. if (this.isCube) {
  30170. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30171. }
  30172. else {
  30173. var size = {
  30174. width: this.width,
  30175. height: this.height
  30176. };
  30177. proxy = this._engine.createRenderTargetTexture(size, options);
  30178. }
  30179. proxy._swapAndDie(this);
  30180. this.isReady = true;
  30181. return;
  30182. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30183. var depthTextureOptions = {
  30184. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30185. comparisonFunction: this._comparisonFunction,
  30186. generateStencil: this._generateStencilBuffer,
  30187. isCube: this.isCube
  30188. };
  30189. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30190. proxy._swapAndDie(this);
  30191. this.isReady = true;
  30192. return;
  30193. case InternalTexture.DATASOURCE_CUBE:
  30194. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30195. _this.isReady = true;
  30196. }, null, this.format, this._extension);
  30197. proxy._swapAndDie(this);
  30198. return;
  30199. case InternalTexture.DATASOURCE_CUBERAW:
  30200. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30201. proxy._swapAndDie(this);
  30202. this.isReady = true;
  30203. return;
  30204. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30205. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30206. if (proxy) {
  30207. proxy._swapAndDie(_this);
  30208. }
  30209. _this.isReady = true;
  30210. }, null, this.format, this._extension);
  30211. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30212. return;
  30213. }
  30214. };
  30215. InternalTexture.prototype._swapAndDie = function (target) {
  30216. target._webGLTexture = this._webGLTexture;
  30217. if (this._framebuffer) {
  30218. target._framebuffer = this._framebuffer;
  30219. }
  30220. if (this._depthStencilBuffer) {
  30221. target._depthStencilBuffer = this._depthStencilBuffer;
  30222. }
  30223. if (this._lodTextureHigh) {
  30224. if (target._lodTextureHigh) {
  30225. target._lodTextureHigh.dispose();
  30226. }
  30227. target._lodTextureHigh = this._lodTextureHigh;
  30228. }
  30229. if (this._lodTextureMid) {
  30230. if (target._lodTextureMid) {
  30231. target._lodTextureMid.dispose();
  30232. }
  30233. target._lodTextureMid = this._lodTextureMid;
  30234. }
  30235. if (this._lodTextureLow) {
  30236. if (target._lodTextureLow) {
  30237. target._lodTextureLow.dispose();
  30238. }
  30239. target._lodTextureLow = this._lodTextureLow;
  30240. }
  30241. var cache = this._engine.getLoadedTexturesCache();
  30242. var index = cache.indexOf(this);
  30243. if (index !== -1) {
  30244. cache.splice(index, 1);
  30245. }
  30246. };
  30247. /**
  30248. * Dispose the current allocated resources
  30249. */
  30250. InternalTexture.prototype.dispose = function () {
  30251. if (!this._webGLTexture) {
  30252. return;
  30253. }
  30254. this._references--;
  30255. if (this._references === 0) {
  30256. this._engine._releaseTexture(this);
  30257. this._webGLTexture = null;
  30258. this.previous = null;
  30259. this.next = null;
  30260. }
  30261. };
  30262. /**
  30263. * The source of the texture data is unknown
  30264. */
  30265. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30266. /**
  30267. * Texture data comes from an URL
  30268. */
  30269. InternalTexture.DATASOURCE_URL = 1;
  30270. /**
  30271. * Texture data is only used for temporary storage
  30272. */
  30273. InternalTexture.DATASOURCE_TEMP = 2;
  30274. /**
  30275. * Texture data comes from raw data (ArrayBuffer)
  30276. */
  30277. InternalTexture.DATASOURCE_RAW = 3;
  30278. /**
  30279. * Texture content is dynamic (video or dynamic texture)
  30280. */
  30281. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30282. /**
  30283. * Texture content is generated by rendering to it
  30284. */
  30285. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30286. /**
  30287. * Texture content is part of a multi render target process
  30288. */
  30289. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30290. /**
  30291. * Texture data comes from a cube data file
  30292. */
  30293. InternalTexture.DATASOURCE_CUBE = 7;
  30294. /**
  30295. * Texture data comes from a raw cube data
  30296. */
  30297. InternalTexture.DATASOURCE_CUBERAW = 8;
  30298. /**
  30299. * Texture data come from a prefiltered cube data file
  30300. */
  30301. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30302. /**
  30303. * Texture content is raw 3D data
  30304. */
  30305. InternalTexture.DATASOURCE_RAW3D = 10;
  30306. /**
  30307. * Texture content is a depth texture
  30308. */
  30309. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30310. return InternalTexture;
  30311. }());
  30312. BABYLON.InternalTexture = InternalTexture;
  30313. })(BABYLON || (BABYLON = {}));
  30314. //# sourceMappingURL=babylon.internalTexture.js.map
  30315. var BABYLON;
  30316. (function (BABYLON) {
  30317. var BaseTexture = /** @class */ (function () {
  30318. function BaseTexture(scene) {
  30319. this._hasAlpha = false;
  30320. this.getAlphaFromRGB = false;
  30321. this.level = 1;
  30322. this.coordinatesIndex = 0;
  30323. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30324. /**
  30325. * | Value | Type | Description |
  30326. * | ----- | ------------------ | ----------- |
  30327. * | 0 | CLAMP_ADDRESSMODE | |
  30328. * | 1 | WRAP_ADDRESSMODE | |
  30329. * | 2 | MIRROR_ADDRESSMODE | |
  30330. */
  30331. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30332. /**
  30333. * | Value | Type | Description |
  30334. * | ----- | ------------------ | ----------- |
  30335. * | 0 | CLAMP_ADDRESSMODE | |
  30336. * | 1 | WRAP_ADDRESSMODE | |
  30337. * | 2 | MIRROR_ADDRESSMODE | |
  30338. */
  30339. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30340. /**
  30341. * | Value | Type | Description |
  30342. * | ----- | ------------------ | ----------- |
  30343. * | 0 | CLAMP_ADDRESSMODE | |
  30344. * | 1 | WRAP_ADDRESSMODE | |
  30345. * | 2 | MIRROR_ADDRESSMODE | |
  30346. */
  30347. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30348. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30349. this.isCube = false;
  30350. this.is3D = false;
  30351. this.gammaSpace = true;
  30352. this.invertZ = false;
  30353. this.lodLevelInAlpha = false;
  30354. this.isRenderTarget = false;
  30355. this.animations = new Array();
  30356. /**
  30357. * An event triggered when the texture is disposed.
  30358. */
  30359. this.onDisposeObservable = new BABYLON.Observable();
  30360. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30361. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30362. if (this._scene) {
  30363. this._scene.textures.push(this);
  30364. }
  30365. this._uid = null;
  30366. }
  30367. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30368. get: function () {
  30369. return this._hasAlpha;
  30370. },
  30371. set: function (value) {
  30372. if (this._hasAlpha === value) {
  30373. return;
  30374. }
  30375. this._hasAlpha = value;
  30376. if (this._scene) {
  30377. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30378. }
  30379. },
  30380. enumerable: true,
  30381. configurable: true
  30382. });
  30383. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30384. get: function () {
  30385. return this._coordinatesMode;
  30386. },
  30387. /**
  30388. * How a texture is mapped.
  30389. *
  30390. * | Value | Type | Description |
  30391. * | ----- | ----------------------------------- | ----------- |
  30392. * | 0 | EXPLICIT_MODE | |
  30393. * | 1 | SPHERICAL_MODE | |
  30394. * | 2 | PLANAR_MODE | |
  30395. * | 3 | CUBIC_MODE | |
  30396. * | 4 | PROJECTION_MODE | |
  30397. * | 5 | SKYBOX_MODE | |
  30398. * | 6 | INVCUBIC_MODE | |
  30399. * | 7 | EQUIRECTANGULAR_MODE | |
  30400. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30401. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30402. */
  30403. set: function (value) {
  30404. if (this._coordinatesMode === value) {
  30405. return;
  30406. }
  30407. this._coordinatesMode = value;
  30408. if (this._scene) {
  30409. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30410. }
  30411. },
  30412. enumerable: true,
  30413. configurable: true
  30414. });
  30415. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30416. /**
  30417. * Gets whether or not the texture contains RGBD data.
  30418. */
  30419. get: function () {
  30420. return this._texture != null && this._texture._isRGBD;
  30421. },
  30422. enumerable: true,
  30423. configurable: true
  30424. });
  30425. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30426. get: function () {
  30427. if (this._texture)
  30428. return this._texture._lodGenerationOffset;
  30429. return 0.0;
  30430. },
  30431. set: function (value) {
  30432. if (this._texture)
  30433. this._texture._lodGenerationOffset = value;
  30434. },
  30435. enumerable: true,
  30436. configurable: true
  30437. });
  30438. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30439. get: function () {
  30440. if (this._texture)
  30441. return this._texture._lodGenerationScale;
  30442. return 0.0;
  30443. },
  30444. set: function (value) {
  30445. if (this._texture)
  30446. this._texture._lodGenerationScale = value;
  30447. },
  30448. enumerable: true,
  30449. configurable: true
  30450. });
  30451. Object.defineProperty(BaseTexture.prototype, "uid", {
  30452. get: function () {
  30453. if (!this._uid) {
  30454. this._uid = BABYLON.Tools.RandomId();
  30455. }
  30456. return this._uid;
  30457. },
  30458. enumerable: true,
  30459. configurable: true
  30460. });
  30461. BaseTexture.prototype.toString = function () {
  30462. return this.name;
  30463. };
  30464. BaseTexture.prototype.getClassName = function () {
  30465. return "BaseTexture";
  30466. };
  30467. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30468. set: function (callback) {
  30469. if (this._onDisposeObserver) {
  30470. this.onDisposeObservable.remove(this._onDisposeObserver);
  30471. }
  30472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30478. get: function () {
  30479. return true;
  30480. },
  30481. enumerable: true,
  30482. configurable: true
  30483. });
  30484. BaseTexture.prototype.getScene = function () {
  30485. return this._scene;
  30486. };
  30487. BaseTexture.prototype.getTextureMatrix = function () {
  30488. return BABYLON.Matrix.IdentityReadOnly;
  30489. };
  30490. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30491. return BABYLON.Matrix.IdentityReadOnly;
  30492. };
  30493. BaseTexture.prototype.getInternalTexture = function () {
  30494. return this._texture;
  30495. };
  30496. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30497. return !this.isBlocking || this.isReady();
  30498. };
  30499. BaseTexture.prototype.isReady = function () {
  30500. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30501. this.delayLoad();
  30502. return false;
  30503. }
  30504. if (this._texture) {
  30505. return this._texture.isReady;
  30506. }
  30507. return false;
  30508. };
  30509. BaseTexture.prototype.getSize = function () {
  30510. if (this._texture && this._texture.width) {
  30511. return new BABYLON.Size(this._texture.width, this._texture.height);
  30512. }
  30513. if (this._texture && this._texture._size) {
  30514. return new BABYLON.Size(this._texture._size, this._texture._size);
  30515. }
  30516. return BABYLON.Size.Zero();
  30517. };
  30518. BaseTexture.prototype.getBaseSize = function () {
  30519. if (!this.isReady() || !this._texture)
  30520. return BABYLON.Size.Zero();
  30521. if (this._texture._size) {
  30522. return new BABYLON.Size(this._texture._size, this._texture._size);
  30523. }
  30524. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30525. };
  30526. BaseTexture.prototype.scale = function (ratio) {
  30527. };
  30528. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30529. get: function () {
  30530. return false;
  30531. },
  30532. enumerable: true,
  30533. configurable: true
  30534. });
  30535. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30536. if (!this._scene) {
  30537. return null;
  30538. }
  30539. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30540. for (var index = 0; index < texturesCache.length; index++) {
  30541. var texturesCacheEntry = texturesCache[index];
  30542. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30543. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30544. texturesCacheEntry.incrementReferences();
  30545. return texturesCacheEntry;
  30546. }
  30547. }
  30548. }
  30549. return null;
  30550. };
  30551. BaseTexture.prototype._rebuild = function () {
  30552. };
  30553. BaseTexture.prototype.delayLoad = function () {
  30554. };
  30555. BaseTexture.prototype.clone = function () {
  30556. return null;
  30557. };
  30558. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30559. get: function () {
  30560. if (!this._texture) {
  30561. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30562. }
  30563. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30564. },
  30565. enumerable: true,
  30566. configurable: true
  30567. });
  30568. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30569. get: function () {
  30570. if (!this._texture) {
  30571. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30572. }
  30573. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30574. },
  30575. enumerable: true,
  30576. configurable: true
  30577. });
  30578. /**
  30579. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30580. * This will returns an RGBA array buffer containing either in values (0-255) or
  30581. * float values (0-1) depending of the underlying buffer type.
  30582. * @param faceIndex The face of the texture to read (in case of cube texture)
  30583. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30584. * @returns The Array buffer containing the pixels data.
  30585. */
  30586. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30587. if (faceIndex === void 0) { faceIndex = 0; }
  30588. if (level === void 0) { level = 0; }
  30589. if (!this._texture) {
  30590. return null;
  30591. }
  30592. var size = this.getSize();
  30593. var width = size.width;
  30594. var height = size.height;
  30595. var scene = this.getScene();
  30596. if (!scene) {
  30597. return null;
  30598. }
  30599. var engine = scene.getEngine();
  30600. if (level != 0) {
  30601. width = width / Math.pow(2, level);
  30602. height = height / Math.pow(2, level);
  30603. width = Math.round(width);
  30604. height = Math.round(height);
  30605. }
  30606. if (this._texture.isCube) {
  30607. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30608. }
  30609. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30610. };
  30611. BaseTexture.prototype.releaseInternalTexture = function () {
  30612. if (this._texture) {
  30613. this._texture.dispose();
  30614. this._texture = null;
  30615. }
  30616. };
  30617. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30618. get: function () {
  30619. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30620. return null;
  30621. }
  30622. if (!this._texture._sphericalPolynomial) {
  30623. this._texture._sphericalPolynomial =
  30624. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30625. }
  30626. return this._texture._sphericalPolynomial;
  30627. },
  30628. set: function (value) {
  30629. if (this._texture) {
  30630. this._texture._sphericalPolynomial = value;
  30631. }
  30632. },
  30633. enumerable: true,
  30634. configurable: true
  30635. });
  30636. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30637. get: function () {
  30638. if (this._texture) {
  30639. return this._texture._lodTextureHigh;
  30640. }
  30641. return null;
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30647. get: function () {
  30648. if (this._texture) {
  30649. return this._texture._lodTextureMid;
  30650. }
  30651. return null;
  30652. },
  30653. enumerable: true,
  30654. configurable: true
  30655. });
  30656. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30657. get: function () {
  30658. if (this._texture) {
  30659. return this._texture._lodTextureLow;
  30660. }
  30661. return null;
  30662. },
  30663. enumerable: true,
  30664. configurable: true
  30665. });
  30666. BaseTexture.prototype.dispose = function () {
  30667. if (!this._scene) {
  30668. return;
  30669. }
  30670. // Animations
  30671. this._scene.stopAnimation(this);
  30672. // Remove from scene
  30673. this._scene._removePendingData(this);
  30674. var index = this._scene.textures.indexOf(this);
  30675. if (index >= 0) {
  30676. this._scene.textures.splice(index, 1);
  30677. }
  30678. if (this._texture === undefined) {
  30679. return;
  30680. }
  30681. // Release
  30682. this.releaseInternalTexture();
  30683. // Callback
  30684. this.onDisposeObservable.notifyObservers(this);
  30685. this.onDisposeObservable.clear();
  30686. };
  30687. BaseTexture.prototype.serialize = function () {
  30688. if (!this.name) {
  30689. return null;
  30690. }
  30691. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30692. // Animations
  30693. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30694. return serializationObject;
  30695. };
  30696. BaseTexture.WhenAllReady = function (textures, callback) {
  30697. var numRemaining = textures.length;
  30698. if (numRemaining === 0) {
  30699. callback();
  30700. return;
  30701. }
  30702. var _loop_1 = function () {
  30703. texture = textures[i];
  30704. if (texture.isReady()) {
  30705. if (--numRemaining === 0) {
  30706. callback();
  30707. }
  30708. }
  30709. else {
  30710. onLoadObservable = texture.onLoadObservable;
  30711. var onLoadCallback_1 = function () {
  30712. onLoadObservable.removeCallback(onLoadCallback_1);
  30713. if (--numRemaining === 0) {
  30714. callback();
  30715. }
  30716. };
  30717. onLoadObservable.add(onLoadCallback_1);
  30718. }
  30719. };
  30720. var texture, onLoadObservable;
  30721. for (var i = 0; i < textures.length; i++) {
  30722. _loop_1();
  30723. }
  30724. };
  30725. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30726. __decorate([
  30727. BABYLON.serialize()
  30728. ], BaseTexture.prototype, "name", void 0);
  30729. __decorate([
  30730. BABYLON.serialize("hasAlpha")
  30731. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30732. __decorate([
  30733. BABYLON.serialize()
  30734. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30735. __decorate([
  30736. BABYLON.serialize()
  30737. ], BaseTexture.prototype, "level", void 0);
  30738. __decorate([
  30739. BABYLON.serialize()
  30740. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30741. __decorate([
  30742. BABYLON.serialize("coordinatesMode")
  30743. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30744. __decorate([
  30745. BABYLON.serialize()
  30746. ], BaseTexture.prototype, "wrapU", void 0);
  30747. __decorate([
  30748. BABYLON.serialize()
  30749. ], BaseTexture.prototype, "wrapV", void 0);
  30750. __decorate([
  30751. BABYLON.serialize()
  30752. ], BaseTexture.prototype, "wrapR", void 0);
  30753. __decorate([
  30754. BABYLON.serialize()
  30755. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30756. __decorate([
  30757. BABYLON.serialize()
  30758. ], BaseTexture.prototype, "isCube", void 0);
  30759. __decorate([
  30760. BABYLON.serialize()
  30761. ], BaseTexture.prototype, "is3D", void 0);
  30762. __decorate([
  30763. BABYLON.serialize()
  30764. ], BaseTexture.prototype, "gammaSpace", void 0);
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], BaseTexture.prototype, "invertZ", void 0);
  30768. __decorate([
  30769. BABYLON.serialize()
  30770. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30771. __decorate([
  30772. BABYLON.serialize()
  30773. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], BaseTexture.prototype, "lodGenerationScale", null);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30780. return BaseTexture;
  30781. }());
  30782. BABYLON.BaseTexture = BaseTexture;
  30783. })(BABYLON || (BABYLON = {}));
  30784. //# sourceMappingURL=babylon.baseTexture.js.map
  30785. var BABYLON;
  30786. (function (BABYLON) {
  30787. var Texture = /** @class */ (function (_super) {
  30788. __extends(Texture, _super);
  30789. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30790. if (noMipmap === void 0) { noMipmap = false; }
  30791. if (invertY === void 0) { invertY = true; }
  30792. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30793. if (onLoad === void 0) { onLoad = null; }
  30794. if (onError === void 0) { onError = null; }
  30795. if (buffer === void 0) { buffer = null; }
  30796. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30797. var _this = _super.call(this, scene) || this;
  30798. _this.uOffset = 0;
  30799. _this.vOffset = 0;
  30800. _this.uScale = 1.0;
  30801. _this.vScale = 1.0;
  30802. _this.uAng = 0;
  30803. _this.vAng = 0;
  30804. _this.wAng = 0;
  30805. /**
  30806. * Defines the center of rotation (U)
  30807. */
  30808. _this.uRotationCenter = 0.5;
  30809. /**
  30810. * Defines the center of rotation (V)
  30811. */
  30812. _this.vRotationCenter = 0.5;
  30813. /**
  30814. * Defines the center of rotation (W)
  30815. */
  30816. _this.wRotationCenter = 0.5;
  30817. _this._isBlocking = true;
  30818. _this.name = url || "";
  30819. _this.url = url;
  30820. _this._noMipmap = noMipmap;
  30821. _this._invertY = invertY;
  30822. _this._samplingMode = samplingMode;
  30823. _this._buffer = buffer;
  30824. _this._deleteBuffer = deleteBuffer;
  30825. if (format) {
  30826. _this._format = format;
  30827. }
  30828. scene = _this.getScene();
  30829. if (!scene) {
  30830. return _this;
  30831. }
  30832. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30833. var load = function () {
  30834. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30835. _this.onLoadObservable.notifyObservers(_this);
  30836. }
  30837. if (onLoad) {
  30838. onLoad();
  30839. }
  30840. if (!_this.isBlocking && scene) {
  30841. scene.resetCachedMaterial();
  30842. }
  30843. };
  30844. if (!_this.url) {
  30845. _this._delayedOnLoad = load;
  30846. _this._delayedOnError = onError;
  30847. return _this;
  30848. }
  30849. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30850. if (!_this._texture) {
  30851. if (!scene.useDelayedTextureLoading) {
  30852. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30853. if (deleteBuffer) {
  30854. delete _this._buffer;
  30855. }
  30856. }
  30857. else {
  30858. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30859. _this._delayedOnLoad = load;
  30860. _this._delayedOnError = onError;
  30861. }
  30862. }
  30863. else {
  30864. if (_this._texture.isReady) {
  30865. BABYLON.Tools.SetImmediate(function () { return load(); });
  30866. }
  30867. else {
  30868. _this._texture.onLoadedObservable.add(load);
  30869. }
  30870. }
  30871. return _this;
  30872. }
  30873. Object.defineProperty(Texture.prototype, "noMipmap", {
  30874. get: function () {
  30875. return this._noMipmap;
  30876. },
  30877. enumerable: true,
  30878. configurable: true
  30879. });
  30880. Object.defineProperty(Texture.prototype, "isBlocking", {
  30881. get: function () {
  30882. return this._isBlocking;
  30883. },
  30884. set: function (value) {
  30885. this._isBlocking = value;
  30886. },
  30887. enumerable: true,
  30888. configurable: true
  30889. });
  30890. Object.defineProperty(Texture.prototype, "samplingMode", {
  30891. get: function () {
  30892. return this._samplingMode;
  30893. },
  30894. enumerable: true,
  30895. configurable: true
  30896. });
  30897. /**
  30898. * Update the url (and optional buffer) of this texture if url was null during construction.
  30899. * @param url the url of the texture
  30900. * @param buffer the buffer of the texture (defaults to null)
  30901. */
  30902. Texture.prototype.updateURL = function (url, buffer) {
  30903. if (buffer === void 0) { buffer = null; }
  30904. if (this.url) {
  30905. throw new Error("URL is already set");
  30906. }
  30907. this.url = url;
  30908. this._buffer = buffer;
  30909. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30910. this.delayLoad();
  30911. };
  30912. Texture.prototype.delayLoad = function () {
  30913. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30914. return;
  30915. }
  30916. var scene = this.getScene();
  30917. if (!scene) {
  30918. return;
  30919. }
  30920. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30921. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30922. if (!this._texture) {
  30923. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30924. if (this._deleteBuffer) {
  30925. delete this._buffer;
  30926. }
  30927. }
  30928. else {
  30929. if (this._delayedOnLoad) {
  30930. if (this._texture.isReady) {
  30931. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30932. }
  30933. else {
  30934. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30935. }
  30936. }
  30937. }
  30938. this._delayedOnLoad = null;
  30939. this._delayedOnError = null;
  30940. };
  30941. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30942. if (!this._texture) {
  30943. return;
  30944. }
  30945. var scene = this.getScene();
  30946. if (!scene) {
  30947. return;
  30948. }
  30949. this._samplingMode = samplingMode;
  30950. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30951. };
  30952. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30953. x *= this.uScale;
  30954. y *= this.vScale;
  30955. x -= this.uRotationCenter * this.uScale;
  30956. y -= this.vRotationCenter * this.vScale;
  30957. z -= this.wRotationCenter;
  30958. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30959. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30960. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30961. t.z += this.wRotationCenter;
  30962. };
  30963. Texture.prototype.getTextureMatrix = function () {
  30964. var _this = this;
  30965. if (this.uOffset === this._cachedUOffset &&
  30966. this.vOffset === this._cachedVOffset &&
  30967. this.uScale === this._cachedUScale &&
  30968. this.vScale === this._cachedVScale &&
  30969. this.uAng === this._cachedUAng &&
  30970. this.vAng === this._cachedVAng &&
  30971. this.wAng === this._cachedWAng) {
  30972. return this._cachedTextureMatrix;
  30973. }
  30974. this._cachedUOffset = this.uOffset;
  30975. this._cachedVOffset = this.vOffset;
  30976. this._cachedUScale = this.uScale;
  30977. this._cachedVScale = this.vScale;
  30978. this._cachedUAng = this.uAng;
  30979. this._cachedVAng = this.vAng;
  30980. this._cachedWAng = this.wAng;
  30981. if (!this._cachedTextureMatrix) {
  30982. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30983. this._rowGenerationMatrix = new BABYLON.Matrix();
  30984. this._t0 = BABYLON.Vector3.Zero();
  30985. this._t1 = BABYLON.Vector3.Zero();
  30986. this._t2 = BABYLON.Vector3.Zero();
  30987. }
  30988. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30989. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30990. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30991. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30992. this._t1.subtractInPlace(this._t0);
  30993. this._t2.subtractInPlace(this._t0);
  30994. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30995. this._cachedTextureMatrix.m[0] = this._t1.x;
  30996. this._cachedTextureMatrix.m[1] = this._t1.y;
  30997. this._cachedTextureMatrix.m[2] = this._t1.z;
  30998. this._cachedTextureMatrix.m[4] = this._t2.x;
  30999. this._cachedTextureMatrix.m[5] = this._t2.y;
  31000. this._cachedTextureMatrix.m[6] = this._t2.z;
  31001. this._cachedTextureMatrix.m[8] = this._t0.x;
  31002. this._cachedTextureMatrix.m[9] = this._t0.y;
  31003. this._cachedTextureMatrix.m[10] = this._t0.z;
  31004. var scene = this.getScene();
  31005. if (!scene) {
  31006. return this._cachedTextureMatrix;
  31007. }
  31008. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31009. return mat.hasTexture(_this);
  31010. });
  31011. return this._cachedTextureMatrix;
  31012. };
  31013. Texture.prototype.getReflectionTextureMatrix = function () {
  31014. var _this = this;
  31015. var scene = this.getScene();
  31016. if (!scene) {
  31017. return this._cachedTextureMatrix;
  31018. }
  31019. if (this.uOffset === this._cachedUOffset &&
  31020. this.vOffset === this._cachedVOffset &&
  31021. this.uScale === this._cachedUScale &&
  31022. this.vScale === this._cachedVScale &&
  31023. this.coordinatesMode === this._cachedCoordinatesMode) {
  31024. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31025. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31026. return this._cachedTextureMatrix;
  31027. }
  31028. }
  31029. else {
  31030. return this._cachedTextureMatrix;
  31031. }
  31032. }
  31033. if (!this._cachedTextureMatrix) {
  31034. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31035. }
  31036. if (!this._projectionModeMatrix) {
  31037. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31038. }
  31039. this._cachedUOffset = this.uOffset;
  31040. this._cachedVOffset = this.vOffset;
  31041. this._cachedUScale = this.uScale;
  31042. this._cachedVScale = this.vScale;
  31043. this._cachedCoordinatesMode = this.coordinatesMode;
  31044. switch (this.coordinatesMode) {
  31045. case Texture.PLANAR_MODE:
  31046. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31047. this._cachedTextureMatrix[0] = this.uScale;
  31048. this._cachedTextureMatrix[5] = this.vScale;
  31049. this._cachedTextureMatrix[12] = this.uOffset;
  31050. this._cachedTextureMatrix[13] = this.vOffset;
  31051. break;
  31052. case Texture.PROJECTION_MODE:
  31053. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31054. this._projectionModeMatrix.m[0] = 0.5;
  31055. this._projectionModeMatrix.m[5] = -0.5;
  31056. this._projectionModeMatrix.m[10] = 0.0;
  31057. this._projectionModeMatrix.m[12] = 0.5;
  31058. this._projectionModeMatrix.m[13] = 0.5;
  31059. this._projectionModeMatrix.m[14] = 1.0;
  31060. this._projectionModeMatrix.m[15] = 1.0;
  31061. var projectionMatrix = scene.getProjectionMatrix();
  31062. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31063. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31064. break;
  31065. default:
  31066. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31067. break;
  31068. }
  31069. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31070. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31071. });
  31072. return this._cachedTextureMatrix;
  31073. };
  31074. Texture.prototype.clone = function () {
  31075. var _this = this;
  31076. return BABYLON.SerializationHelper.Clone(function () {
  31077. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31078. }, this);
  31079. };
  31080. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31081. get: function () {
  31082. if (!this._onLoadObservable) {
  31083. this._onLoadObservable = new BABYLON.Observable();
  31084. }
  31085. return this._onLoadObservable;
  31086. },
  31087. enumerable: true,
  31088. configurable: true
  31089. });
  31090. Texture.prototype.serialize = function () {
  31091. var serializationObject = _super.prototype.serialize.call(this);
  31092. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31093. serializationObject.base64String = this._buffer;
  31094. serializationObject.name = serializationObject.name.replace("data:", "");
  31095. }
  31096. serializationObject.invertY = this._invertY;
  31097. serializationObject.samplingMode = this.samplingMode;
  31098. return serializationObject;
  31099. };
  31100. Texture.prototype.getClassName = function () {
  31101. return "Texture";
  31102. };
  31103. Texture.prototype.dispose = function () {
  31104. _super.prototype.dispose.call(this);
  31105. if (this.onLoadObservable) {
  31106. this.onLoadObservable.clear();
  31107. this._onLoadObservable = null;
  31108. }
  31109. this._delayedOnLoad = null;
  31110. this._delayedOnError = null;
  31111. };
  31112. // Statics
  31113. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31114. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31115. if (onLoad === void 0) { onLoad = null; }
  31116. if (onError === void 0) { onError = null; }
  31117. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31118. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31119. };
  31120. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31121. if (parsedTexture.customType) {
  31122. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31123. // Update Sampling Mode
  31124. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31125. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31126. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31127. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31128. }
  31129. }
  31130. return parsedCustomTexture;
  31131. }
  31132. if (parsedTexture.isCube) {
  31133. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31134. }
  31135. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31136. return null;
  31137. }
  31138. var texture = BABYLON.SerializationHelper.Parse(function () {
  31139. var generateMipMaps = true;
  31140. if (parsedTexture.noMipmap) {
  31141. generateMipMaps = false;
  31142. }
  31143. if (parsedTexture.mirrorPlane) {
  31144. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31145. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31146. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31147. return mirrorTexture;
  31148. }
  31149. else if (parsedTexture.isRenderTarget) {
  31150. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31151. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31152. return renderTargetTexture;
  31153. }
  31154. else {
  31155. var texture;
  31156. if (parsedTexture.base64String) {
  31157. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31158. }
  31159. else {
  31160. var url = rootUrl + parsedTexture.name;
  31161. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31162. url = parsedTexture.url;
  31163. }
  31164. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31165. }
  31166. return texture;
  31167. }
  31168. }, parsedTexture, scene);
  31169. // Update Sampling Mode
  31170. if (parsedTexture.samplingMode) {
  31171. var sampling = parsedTexture.samplingMode;
  31172. if (texture._samplingMode !== sampling) {
  31173. texture.updateSamplingMode(sampling);
  31174. }
  31175. }
  31176. // Animations
  31177. if (parsedTexture.animations) {
  31178. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31179. var parsedAnimation = parsedTexture.animations[animationIndex];
  31180. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31181. }
  31182. }
  31183. return texture;
  31184. };
  31185. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31186. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31187. if (noMipmap === void 0) { noMipmap = false; }
  31188. if (invertY === void 0) { invertY = true; }
  31189. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31190. if (onLoad === void 0) { onLoad = null; }
  31191. if (onError === void 0) { onError = null; }
  31192. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31193. if (name.substr(0, 5) !== "data:") {
  31194. name = "data:" + name;
  31195. }
  31196. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31197. };
  31198. // Constants
  31199. Texture.NEAREST_SAMPLINGMODE = 1;
  31200. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31201. Texture.BILINEAR_SAMPLINGMODE = 2;
  31202. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31203. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31204. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31205. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31206. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31207. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31208. Texture.NEAREST_LINEAR = 7;
  31209. Texture.NEAREST_NEAREST = 8;
  31210. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31211. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31212. Texture.LINEAR_LINEAR = 11;
  31213. Texture.LINEAR_NEAREST = 12;
  31214. Texture.EXPLICIT_MODE = 0;
  31215. Texture.SPHERICAL_MODE = 1;
  31216. Texture.PLANAR_MODE = 2;
  31217. Texture.CUBIC_MODE = 3;
  31218. Texture.PROJECTION_MODE = 4;
  31219. Texture.SKYBOX_MODE = 5;
  31220. Texture.INVCUBIC_MODE = 6;
  31221. Texture.EQUIRECTANGULAR_MODE = 7;
  31222. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31223. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31224. Texture.CLAMP_ADDRESSMODE = 0;
  31225. Texture.WRAP_ADDRESSMODE = 1;
  31226. Texture.MIRROR_ADDRESSMODE = 2;
  31227. /**
  31228. * 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
  31229. */
  31230. Texture.UseSerializedUrlIfAny = false;
  31231. __decorate([
  31232. BABYLON.serialize()
  31233. ], Texture.prototype, "url", void 0);
  31234. __decorate([
  31235. BABYLON.serialize()
  31236. ], Texture.prototype, "uOffset", void 0);
  31237. __decorate([
  31238. BABYLON.serialize()
  31239. ], Texture.prototype, "vOffset", void 0);
  31240. __decorate([
  31241. BABYLON.serialize()
  31242. ], Texture.prototype, "uScale", void 0);
  31243. __decorate([
  31244. BABYLON.serialize()
  31245. ], Texture.prototype, "vScale", void 0);
  31246. __decorate([
  31247. BABYLON.serialize()
  31248. ], Texture.prototype, "uAng", void 0);
  31249. __decorate([
  31250. BABYLON.serialize()
  31251. ], Texture.prototype, "vAng", void 0);
  31252. __decorate([
  31253. BABYLON.serialize()
  31254. ], Texture.prototype, "wAng", void 0);
  31255. __decorate([
  31256. BABYLON.serialize()
  31257. ], Texture.prototype, "uRotationCenter", void 0);
  31258. __decorate([
  31259. BABYLON.serialize()
  31260. ], Texture.prototype, "vRotationCenter", void 0);
  31261. __decorate([
  31262. BABYLON.serialize()
  31263. ], Texture.prototype, "wRotationCenter", void 0);
  31264. __decorate([
  31265. BABYLON.serialize()
  31266. ], Texture.prototype, "isBlocking", null);
  31267. return Texture;
  31268. }(BABYLON.BaseTexture));
  31269. BABYLON.Texture = Texture;
  31270. })(BABYLON || (BABYLON = {}));
  31271. //# sourceMappingURL=babylon.texture.js.map
  31272. var BABYLON;
  31273. (function (BABYLON) {
  31274. /**
  31275. * @hidden
  31276. **/
  31277. var _InstancesBatch = /** @class */ (function () {
  31278. function _InstancesBatch() {
  31279. this.mustReturn = false;
  31280. this.visibleInstances = new Array();
  31281. this.renderSelf = new Array();
  31282. }
  31283. return _InstancesBatch;
  31284. }());
  31285. BABYLON._InstancesBatch = _InstancesBatch;
  31286. var Mesh = /** @class */ (function (_super) {
  31287. __extends(Mesh, _super);
  31288. /**
  31289. * @constructor
  31290. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31291. * @param {Scene} scene The scene to add this mesh to.
  31292. * @param {Node} parent The parent of this mesh, if it has one
  31293. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31294. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31295. * When false, achieved by calling a clone(), also passing False.
  31296. * This will make creation of children, recursive.
  31297. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31298. */
  31299. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31300. if (scene === void 0) { scene = null; }
  31301. if (parent === void 0) { parent = null; }
  31302. if (source === void 0) { source = null; }
  31303. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31304. var _this = _super.call(this, name, scene) || this;
  31305. // Events
  31306. /**
  31307. * An event triggered before rendering the mesh
  31308. */
  31309. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31310. /**
  31311. * An event triggered after rendering the mesh
  31312. */
  31313. _this.onAfterRenderObservable = new BABYLON.Observable();
  31314. /**
  31315. * An event triggered before drawing the mesh
  31316. */
  31317. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31318. // Members
  31319. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31320. _this.instances = new Array();
  31321. _this._LODLevels = new Array();
  31322. _this._visibleInstances = {};
  31323. _this._renderIdForInstances = new Array();
  31324. _this._batchCache = new _InstancesBatch();
  31325. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31326. // Use by builder only to know what orientation were the mesh build in.
  31327. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31328. _this.overrideMaterialSideOrientation = null;
  31329. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31330. // Will be used to save a source mesh reference, If any
  31331. _this._source = null;
  31332. scene = _this.getScene();
  31333. if (source) {
  31334. // Geometry
  31335. if (source._geometry) {
  31336. source._geometry.applyToMesh(_this);
  31337. }
  31338. // Deep copy
  31339. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31340. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31341. // Source mesh
  31342. _this._source = source;
  31343. // Metadata
  31344. if (source.metadata && source.metadata.clone) {
  31345. _this.metadata = source.metadata.clone();
  31346. }
  31347. else {
  31348. _this.metadata = source.metadata;
  31349. }
  31350. // Tags
  31351. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31352. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31353. }
  31354. // Parent
  31355. _this.parent = source.parent;
  31356. // Pivot
  31357. _this.setPivotMatrix(source.getPivotMatrix());
  31358. _this.id = name + "." + source.id;
  31359. // Material
  31360. _this.material = source.material;
  31361. var index;
  31362. if (!doNotCloneChildren) {
  31363. // Children
  31364. var directDescendants = source.getDescendants(true);
  31365. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31366. var child = directDescendants[index_1];
  31367. if (child.clone) {
  31368. child.clone(name + "." + child.name, _this);
  31369. }
  31370. }
  31371. }
  31372. // Physics clone
  31373. var physicsEngine = _this.getScene().getPhysicsEngine();
  31374. if (clonePhysicsImpostor && physicsEngine) {
  31375. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31376. if (impostor) {
  31377. _this.physicsImpostor = impostor.clone(_this);
  31378. }
  31379. }
  31380. // Particles
  31381. for (index = 0; index < scene.particleSystems.length; index++) {
  31382. var system = scene.particleSystems[index];
  31383. if (system.emitter === source) {
  31384. system.clone(system.name, _this);
  31385. }
  31386. }
  31387. _this.computeWorldMatrix(true);
  31388. }
  31389. // Parent
  31390. if (parent !== null) {
  31391. _this.parent = parent;
  31392. }
  31393. return _this;
  31394. }
  31395. Object.defineProperty(Mesh, "FRONTSIDE", {
  31396. /**
  31397. * Mesh side orientation : usually the external or front surface
  31398. */
  31399. get: function () {
  31400. return Mesh._FRONTSIDE;
  31401. },
  31402. enumerable: true,
  31403. configurable: true
  31404. });
  31405. Object.defineProperty(Mesh, "BACKSIDE", {
  31406. /**
  31407. * Mesh side orientation : usually the internal or back surface
  31408. */
  31409. get: function () {
  31410. return Mesh._BACKSIDE;
  31411. },
  31412. enumerable: true,
  31413. configurable: true
  31414. });
  31415. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31416. /**
  31417. * Mesh side orientation : both internal and external or front and back surfaces
  31418. */
  31419. get: function () {
  31420. return Mesh._DOUBLESIDE;
  31421. },
  31422. enumerable: true,
  31423. configurable: true
  31424. });
  31425. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31426. /**
  31427. * Mesh side orientation : by default, `FRONTSIDE`
  31428. */
  31429. get: function () {
  31430. return Mesh._DEFAULTSIDE;
  31431. },
  31432. enumerable: true,
  31433. configurable: true
  31434. });
  31435. Object.defineProperty(Mesh, "NO_CAP", {
  31436. /**
  31437. * Mesh cap setting : no cap
  31438. */
  31439. get: function () {
  31440. return Mesh._NO_CAP;
  31441. },
  31442. enumerable: true,
  31443. configurable: true
  31444. });
  31445. Object.defineProperty(Mesh, "CAP_START", {
  31446. /**
  31447. * Mesh cap setting : one cap at the beginning of the mesh
  31448. */
  31449. get: function () {
  31450. return Mesh._CAP_START;
  31451. },
  31452. enumerable: true,
  31453. configurable: true
  31454. });
  31455. Object.defineProperty(Mesh, "CAP_END", {
  31456. /**
  31457. * Mesh cap setting : one cap at the end of the mesh
  31458. */
  31459. get: function () {
  31460. return Mesh._CAP_END;
  31461. },
  31462. enumerable: true,
  31463. configurable: true
  31464. });
  31465. Object.defineProperty(Mesh, "CAP_ALL", {
  31466. /**
  31467. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31468. */
  31469. get: function () {
  31470. return Mesh._CAP_ALL;
  31471. },
  31472. enumerable: true,
  31473. configurable: true
  31474. });
  31475. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31476. set: function (callback) {
  31477. if (this._onBeforeDrawObserver) {
  31478. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31479. }
  31480. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31481. },
  31482. enumerable: true,
  31483. configurable: true
  31484. });
  31485. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31486. get: function () {
  31487. return this._morphTargetManager;
  31488. },
  31489. set: function (value) {
  31490. if (this._morphTargetManager === value) {
  31491. return;
  31492. }
  31493. this._morphTargetManager = value;
  31494. this._syncGeometryWithMorphTargetManager();
  31495. },
  31496. enumerable: true,
  31497. configurable: true
  31498. });
  31499. Object.defineProperty(Mesh.prototype, "source", {
  31500. get: function () {
  31501. return this._source;
  31502. },
  31503. enumerable: true,
  31504. configurable: true
  31505. });
  31506. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31507. get: function () {
  31508. return this._unIndexed;
  31509. },
  31510. set: function (value) {
  31511. if (this._unIndexed !== value) {
  31512. this._unIndexed = value;
  31513. this._markSubMeshesAsAttributesDirty();
  31514. }
  31515. },
  31516. enumerable: true,
  31517. configurable: true
  31518. });
  31519. // Methods
  31520. /**
  31521. * Returns the string "Mesh".
  31522. */
  31523. Mesh.prototype.getClassName = function () {
  31524. return "Mesh";
  31525. };
  31526. /**
  31527. * Returns a string.
  31528. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31529. */
  31530. Mesh.prototype.toString = function (fullDetails) {
  31531. var ret = _super.prototype.toString.call(this, fullDetails);
  31532. ret += ", n vertices: " + this.getTotalVertices();
  31533. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31534. if (this.animations) {
  31535. for (var i = 0; i < this.animations.length; i++) {
  31536. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31537. }
  31538. }
  31539. if (fullDetails) {
  31540. if (this._geometry) {
  31541. var ib = this.getIndices();
  31542. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31543. if (vb && ib) {
  31544. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31545. }
  31546. }
  31547. else {
  31548. ret += ", flat shading: UNKNOWN";
  31549. }
  31550. }
  31551. return ret;
  31552. };
  31553. Mesh.prototype._unBindEffect = function () {
  31554. _super.prototype._unBindEffect.call(this);
  31555. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31556. var instance = _a[_i];
  31557. instance._unBindEffect();
  31558. }
  31559. };
  31560. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31561. /**
  31562. * True if the mesh has some Levels Of Details (LOD).
  31563. * Returns a boolean.
  31564. */
  31565. get: function () {
  31566. return this._LODLevels.length > 0;
  31567. },
  31568. enumerable: true,
  31569. configurable: true
  31570. });
  31571. /**
  31572. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31573. * @returns an array of {BABYLON.MeshLODLevel}
  31574. */
  31575. Mesh.prototype.getLODLevels = function () {
  31576. return this._LODLevels;
  31577. };
  31578. Mesh.prototype._sortLODLevels = function () {
  31579. this._LODLevels.sort(function (a, b) {
  31580. if (a.distance < b.distance) {
  31581. return 1;
  31582. }
  31583. if (a.distance > b.distance) {
  31584. return -1;
  31585. }
  31586. return 0;
  31587. });
  31588. };
  31589. /**
  31590. * Add a mesh as LOD level triggered at the given distance.
  31591. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31592. * @param distance The distance from the center of the object to show this level
  31593. * @param mesh The mesh to be added as LOD level (can be null)
  31594. * @return This mesh (for chaining)
  31595. */
  31596. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31597. if (mesh && mesh._masterMesh) {
  31598. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31599. return this;
  31600. }
  31601. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31602. this._LODLevels.push(level);
  31603. if (mesh) {
  31604. mesh._masterMesh = this;
  31605. }
  31606. this._sortLODLevels();
  31607. return this;
  31608. };
  31609. /**
  31610. * Returns the LOD level mesh at the passed distance or null if not found.
  31611. * It is related to the method `addLODLevel(distance, mesh)`.
  31612. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31613. * Returns an object Mesh or `null`.
  31614. */
  31615. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31616. for (var index = 0; index < this._LODLevels.length; index++) {
  31617. var level = this._LODLevels[index];
  31618. if (level.distance === distance) {
  31619. return level.mesh;
  31620. }
  31621. }
  31622. return null;
  31623. };
  31624. /**
  31625. * Remove a mesh from the LOD array
  31626. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31627. * @param {Mesh} mesh The mesh to be removed.
  31628. * @return {Mesh} This mesh (for chaining)
  31629. */
  31630. Mesh.prototype.removeLODLevel = function (mesh) {
  31631. for (var index = 0; index < this._LODLevels.length; index++) {
  31632. if (this._LODLevels[index].mesh === mesh) {
  31633. this._LODLevels.splice(index, 1);
  31634. if (mesh) {
  31635. mesh._masterMesh = null;
  31636. }
  31637. }
  31638. }
  31639. this._sortLODLevels();
  31640. return this;
  31641. };
  31642. /**
  31643. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31644. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31645. */
  31646. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31647. if (!this._LODLevels || this._LODLevels.length === 0) {
  31648. return this;
  31649. }
  31650. var bSphere;
  31651. if (boundingSphere) {
  31652. bSphere = boundingSphere;
  31653. }
  31654. else {
  31655. var boundingInfo = this.getBoundingInfo();
  31656. bSphere = boundingInfo.boundingSphere;
  31657. }
  31658. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31659. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31660. if (this.onLODLevelSelection) {
  31661. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31662. }
  31663. return this;
  31664. }
  31665. for (var index = 0; index < this._LODLevels.length; index++) {
  31666. var level = this._LODLevels[index];
  31667. if (level.distance < distanceToCamera) {
  31668. if (level.mesh) {
  31669. level.mesh._preActivate();
  31670. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31671. }
  31672. if (this.onLODLevelSelection) {
  31673. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31674. }
  31675. return level.mesh;
  31676. }
  31677. }
  31678. if (this.onLODLevelSelection) {
  31679. this.onLODLevelSelection(distanceToCamera, this, this);
  31680. }
  31681. return this;
  31682. };
  31683. Object.defineProperty(Mesh.prototype, "geometry", {
  31684. /**
  31685. * Returns the mesh internal Geometry object.
  31686. */
  31687. get: function () {
  31688. return this._geometry;
  31689. },
  31690. enumerable: true,
  31691. configurable: true
  31692. });
  31693. /**
  31694. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31695. */
  31696. Mesh.prototype.getTotalVertices = function () {
  31697. if (this._geometry === null || this._geometry === undefined) {
  31698. return 0;
  31699. }
  31700. return this._geometry.getTotalVertices();
  31701. };
  31702. /**
  31703. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31704. * 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.
  31705. * You can force the copy with forceCopy === true
  31706. * Returns null if the mesh has no geometry or no vertex buffer.
  31707. * Possible `kind` values :
  31708. * - BABYLON.VertexBuffer.PositionKind
  31709. * - BABYLON.VertexBuffer.UVKind
  31710. * - BABYLON.VertexBuffer.UV2Kind
  31711. * - BABYLON.VertexBuffer.UV3Kind
  31712. * - BABYLON.VertexBuffer.UV4Kind
  31713. * - BABYLON.VertexBuffer.UV5Kind
  31714. * - BABYLON.VertexBuffer.UV6Kind
  31715. * - BABYLON.VertexBuffer.ColorKind
  31716. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31717. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31718. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31719. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31720. */
  31721. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31722. if (!this._geometry) {
  31723. return null;
  31724. }
  31725. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31726. };
  31727. /**
  31728. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31729. * Returns `null` if the mesh has no geometry.
  31730. * Possible `kind` values :
  31731. * - BABYLON.VertexBuffer.PositionKind
  31732. * - BABYLON.VertexBuffer.UVKind
  31733. * - BABYLON.VertexBuffer.UV2Kind
  31734. * - BABYLON.VertexBuffer.UV3Kind
  31735. * - BABYLON.VertexBuffer.UV4Kind
  31736. * - BABYLON.VertexBuffer.UV5Kind
  31737. * - BABYLON.VertexBuffer.UV6Kind
  31738. * - BABYLON.VertexBuffer.ColorKind
  31739. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31740. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31741. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31742. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31743. */
  31744. Mesh.prototype.getVertexBuffer = function (kind) {
  31745. if (!this._geometry) {
  31746. return null;
  31747. }
  31748. return this._geometry.getVertexBuffer(kind);
  31749. };
  31750. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31751. if (!this._geometry) {
  31752. if (this._delayInfo) {
  31753. return this._delayInfo.indexOf(kind) !== -1;
  31754. }
  31755. return false;
  31756. }
  31757. return this._geometry.isVerticesDataPresent(kind);
  31758. };
  31759. /**
  31760. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31761. * Possible `kind` values :
  31762. * - BABYLON.VertexBuffer.PositionKind
  31763. * - BABYLON.VertexBuffer.UVKind
  31764. * - BABYLON.VertexBuffer.UV2Kind
  31765. * - BABYLON.VertexBuffer.UV3Kind
  31766. * - BABYLON.VertexBuffer.UV4Kind
  31767. * - BABYLON.VertexBuffer.UV5Kind
  31768. * - BABYLON.VertexBuffer.UV6Kind
  31769. * - BABYLON.VertexBuffer.ColorKind
  31770. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31771. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31772. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31773. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31774. */
  31775. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31776. if (!this._geometry) {
  31777. if (this._delayInfo) {
  31778. return this._delayInfo.indexOf(kind) !== -1;
  31779. }
  31780. return false;
  31781. }
  31782. return this._geometry.isVertexBufferUpdatable(kind);
  31783. };
  31784. /**
  31785. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31786. * Possible `kind` values :
  31787. * - BABYLON.VertexBuffer.PositionKind
  31788. * - BABYLON.VertexBuffer.UVKind
  31789. * - BABYLON.VertexBuffer.UV2Kind
  31790. * - BABYLON.VertexBuffer.UV3Kind
  31791. * - BABYLON.VertexBuffer.UV4Kind
  31792. * - BABYLON.VertexBuffer.UV5Kind
  31793. * - BABYLON.VertexBuffer.UV6Kind
  31794. * - BABYLON.VertexBuffer.ColorKind
  31795. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31796. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31797. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31798. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31799. */
  31800. Mesh.prototype.getVerticesDataKinds = function () {
  31801. if (!this._geometry) {
  31802. var result = new Array();
  31803. if (this._delayInfo) {
  31804. this._delayInfo.forEach(function (kind, index, array) {
  31805. result.push(kind);
  31806. });
  31807. }
  31808. return result;
  31809. }
  31810. return this._geometry.getVerticesDataKinds();
  31811. };
  31812. /**
  31813. * Returns a positive integer : the total number of indices in this mesh geometry.
  31814. * Returns zero if the mesh has no geometry.
  31815. */
  31816. Mesh.prototype.getTotalIndices = function () {
  31817. if (!this._geometry) {
  31818. return 0;
  31819. }
  31820. return this._geometry.getTotalIndices();
  31821. };
  31822. /**
  31823. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31824. * 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.
  31825. * Returns an empty array if the mesh has no geometry.
  31826. */
  31827. Mesh.prototype.getIndices = function (copyWhenShared) {
  31828. if (!this._geometry) {
  31829. return [];
  31830. }
  31831. return this._geometry.getIndices(copyWhenShared);
  31832. };
  31833. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31834. get: function () {
  31835. return this._masterMesh !== null && this._masterMesh !== undefined;
  31836. },
  31837. enumerable: true,
  31838. configurable: true
  31839. });
  31840. /**
  31841. * Determine if the current mesh is ready to be rendered
  31842. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31843. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31844. * @returns true if all associated assets are ready (material, textures, shaders)
  31845. */
  31846. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31847. if (completeCheck === void 0) { completeCheck = false; }
  31848. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31849. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31850. return false;
  31851. }
  31852. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31853. return false;
  31854. }
  31855. if (!this.subMeshes || this.subMeshes.length === 0) {
  31856. return true;
  31857. }
  31858. if (!completeCheck) {
  31859. return true;
  31860. }
  31861. var engine = this.getEngine();
  31862. var scene = this.getScene();
  31863. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31864. this.computeWorldMatrix();
  31865. var mat = this.material || scene.defaultMaterial;
  31866. if (mat) {
  31867. if (mat.storeEffectOnSubMeshes) {
  31868. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31869. var subMesh = _a[_i];
  31870. var effectiveMaterial = subMesh.getMaterial();
  31871. if (effectiveMaterial) {
  31872. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31873. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31874. return false;
  31875. }
  31876. }
  31877. else {
  31878. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31879. return false;
  31880. }
  31881. }
  31882. }
  31883. }
  31884. }
  31885. else {
  31886. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31887. return false;
  31888. }
  31889. }
  31890. }
  31891. // Shadows
  31892. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31893. var light = _c[_b];
  31894. var generator = light.getShadowGenerator();
  31895. if (generator) {
  31896. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31897. var subMesh = _e[_d];
  31898. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31899. return false;
  31900. }
  31901. }
  31902. }
  31903. }
  31904. // LOD
  31905. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31906. var lod = _g[_f];
  31907. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31908. return false;
  31909. }
  31910. }
  31911. return true;
  31912. };
  31913. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31914. /**
  31915. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31916. * This property is pertinent only for updatable parametric shapes.
  31917. */
  31918. get: function () {
  31919. return this._areNormalsFrozen;
  31920. },
  31921. enumerable: true,
  31922. configurable: true
  31923. });
  31924. /**
  31925. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31926. * It has no effect at all on other shapes.
  31927. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31928. * Returns the Mesh.
  31929. */
  31930. Mesh.prototype.freezeNormals = function () {
  31931. this._areNormalsFrozen = true;
  31932. return this;
  31933. };
  31934. /**
  31935. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31936. * It has no effect at all on other shapes.
  31937. * It reactivates the mesh normals computation if it was previously frozen.
  31938. * Returns the Mesh.
  31939. */
  31940. Mesh.prototype.unfreezeNormals = function () {
  31941. this._areNormalsFrozen = false;
  31942. return this;
  31943. };
  31944. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31945. /**
  31946. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31947. */
  31948. set: function (count) {
  31949. this._overridenInstanceCount = count;
  31950. },
  31951. enumerable: true,
  31952. configurable: true
  31953. });
  31954. // Methods
  31955. Mesh.prototype._preActivate = function () {
  31956. var sceneRenderId = this.getScene().getRenderId();
  31957. if (this._preActivateId === sceneRenderId) {
  31958. return this;
  31959. }
  31960. this._preActivateId = sceneRenderId;
  31961. this._visibleInstances = null;
  31962. return this;
  31963. };
  31964. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31965. if (this._visibleInstances) {
  31966. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31967. }
  31968. return this;
  31969. };
  31970. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31971. if (!this._visibleInstances) {
  31972. this._visibleInstances = {};
  31973. this._visibleInstances.defaultRenderId = renderId;
  31974. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31975. }
  31976. if (!this._visibleInstances[renderId]) {
  31977. this._visibleInstances[renderId] = new Array();
  31978. }
  31979. this._visibleInstances[renderId].push(instance);
  31980. return this;
  31981. };
  31982. /**
  31983. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31984. * This means the mesh underlying bounding box and sphere are recomputed.
  31985. * Returns the Mesh.
  31986. */
  31987. Mesh.prototype.refreshBoundingInfo = function () {
  31988. return this._refreshBoundingInfo(false);
  31989. };
  31990. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31991. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31992. return this;
  31993. }
  31994. var data = this._getPositionData(applySkeleton);
  31995. if (data) {
  31996. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31997. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31998. }
  31999. if (this.subMeshes) {
  32000. for (var index = 0; index < this.subMeshes.length; index++) {
  32001. this.subMeshes[index].refreshBoundingInfo();
  32002. }
  32003. }
  32004. this._updateBoundingInfo();
  32005. return this;
  32006. };
  32007. Mesh.prototype._getPositionData = function (applySkeleton) {
  32008. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32009. if (data && applySkeleton && this.skeleton) {
  32010. data = BABYLON.Tools.Slice(data);
  32011. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32012. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32013. if (matricesWeightsData && matricesIndicesData) {
  32014. var needExtras = this.numBoneInfluencers > 4;
  32015. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32016. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32017. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32018. var tempVector = BABYLON.Tmp.Vector3[0];
  32019. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32020. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32021. var matWeightIdx = 0;
  32022. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32023. finalMatrix.reset();
  32024. var inf;
  32025. var weight;
  32026. for (inf = 0; inf < 4; inf++) {
  32027. weight = matricesWeightsData[matWeightIdx + inf];
  32028. if (weight <= 0)
  32029. break;
  32030. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32031. finalMatrix.addToSelf(tempMatrix);
  32032. }
  32033. if (needExtras) {
  32034. for (inf = 0; inf < 4; inf++) {
  32035. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32036. if (weight <= 0)
  32037. break;
  32038. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32039. finalMatrix.addToSelf(tempMatrix);
  32040. }
  32041. }
  32042. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32043. tempVector.toArray(data, index);
  32044. }
  32045. }
  32046. }
  32047. return data;
  32048. };
  32049. Mesh.prototype._createGlobalSubMesh = function (force) {
  32050. var totalVertices = this.getTotalVertices();
  32051. if (!totalVertices || !this.getIndices()) {
  32052. return null;
  32053. }
  32054. // Check if we need to recreate the submeshes
  32055. if (this.subMeshes && this.subMeshes.length > 0) {
  32056. var ib = this.getIndices();
  32057. if (!ib) {
  32058. return null;
  32059. }
  32060. var totalIndices = ib.length;
  32061. var needToRecreate = false;
  32062. if (force) {
  32063. needToRecreate = true;
  32064. }
  32065. else {
  32066. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32067. var submesh = _a[_i];
  32068. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32069. needToRecreate = true;
  32070. break;
  32071. }
  32072. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32073. needToRecreate = true;
  32074. break;
  32075. }
  32076. }
  32077. }
  32078. if (!needToRecreate) {
  32079. return this.subMeshes[0];
  32080. }
  32081. }
  32082. this.releaseSubMeshes();
  32083. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32084. };
  32085. Mesh.prototype.subdivide = function (count) {
  32086. if (count < 1) {
  32087. return;
  32088. }
  32089. var totalIndices = this.getTotalIndices();
  32090. var subdivisionSize = (totalIndices / count) | 0;
  32091. var offset = 0;
  32092. // Ensure that subdivisionSize is a multiple of 3
  32093. while (subdivisionSize % 3 !== 0) {
  32094. subdivisionSize++;
  32095. }
  32096. this.releaseSubMeshes();
  32097. for (var index = 0; index < count; index++) {
  32098. if (offset >= totalIndices) {
  32099. break;
  32100. }
  32101. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32102. offset += subdivisionSize;
  32103. }
  32104. this.synchronizeInstances();
  32105. };
  32106. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32107. if (updatable === void 0) { updatable = false; }
  32108. if (!this._geometry) {
  32109. var vertexData = new BABYLON.VertexData();
  32110. vertexData.set(data, kind);
  32111. var scene = this.getScene();
  32112. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32113. }
  32114. else {
  32115. this._geometry.setVerticesData(kind, data, updatable, stride);
  32116. }
  32117. return this;
  32118. };
  32119. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32120. if (updatable === void 0) { updatable = true; }
  32121. var vb = this.getVertexBuffer(kind);
  32122. if (!vb || vb.isUpdatable() === updatable) {
  32123. return;
  32124. }
  32125. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32126. };
  32127. /**
  32128. * Sets the mesh VertexBuffer.
  32129. * Returns the Mesh.
  32130. */
  32131. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32132. if (!this._geometry) {
  32133. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32134. }
  32135. this._geometry.setVerticesBuffer(buffer);
  32136. return this;
  32137. };
  32138. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32139. if (!this._geometry) {
  32140. return this;
  32141. }
  32142. if (!makeItUnique) {
  32143. this._geometry.updateVerticesData(kind, data, updateExtends);
  32144. }
  32145. else {
  32146. this.makeGeometryUnique();
  32147. this.updateVerticesData(kind, data, updateExtends, false);
  32148. }
  32149. return this;
  32150. };
  32151. /**
  32152. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32153. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32154. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32155. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32156. * Returns the Mesh.
  32157. */
  32158. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32159. if (computeNormals === void 0) { computeNormals = true; }
  32160. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32161. if (!positions) {
  32162. return this;
  32163. }
  32164. positionFunction(positions);
  32165. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32166. if (computeNormals) {
  32167. var indices = this.getIndices();
  32168. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32169. if (!normals) {
  32170. return this;
  32171. }
  32172. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32173. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32174. }
  32175. return this;
  32176. };
  32177. /**
  32178. * Creates a un-shared specific occurence of the geometry for the mesh.
  32179. * Returns the Mesh.
  32180. */
  32181. Mesh.prototype.makeGeometryUnique = function () {
  32182. if (!this._geometry) {
  32183. return this;
  32184. }
  32185. var oldGeometry = this._geometry;
  32186. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32187. oldGeometry.releaseForMesh(this, true);
  32188. geometry.applyToMesh(this);
  32189. return this;
  32190. };
  32191. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32192. if (totalVertices === void 0) { totalVertices = null; }
  32193. if (updatable === void 0) { updatable = false; }
  32194. if (!this._geometry) {
  32195. var vertexData = new BABYLON.VertexData();
  32196. vertexData.indices = indices;
  32197. var scene = this.getScene();
  32198. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32199. }
  32200. else {
  32201. this._geometry.setIndices(indices, totalVertices, updatable);
  32202. }
  32203. return this;
  32204. };
  32205. /**
  32206. * Update the current index buffer
  32207. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32208. * Returns the Mesh.
  32209. */
  32210. Mesh.prototype.updateIndices = function (indices, offset) {
  32211. if (!this._geometry) {
  32212. return this;
  32213. }
  32214. this._geometry.updateIndices(indices, offset);
  32215. return this;
  32216. };
  32217. /**
  32218. * Invert the geometry to move from a right handed system to a left handed one.
  32219. * Returns the Mesh.
  32220. */
  32221. Mesh.prototype.toLeftHanded = function () {
  32222. if (!this._geometry) {
  32223. return this;
  32224. }
  32225. this._geometry.toLeftHanded();
  32226. return this;
  32227. };
  32228. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32229. if (!this._geometry) {
  32230. return this;
  32231. }
  32232. var engine = this.getScene().getEngine();
  32233. // Wireframe
  32234. var indexToBind;
  32235. if (this._unIndexed) {
  32236. indexToBind = null;
  32237. }
  32238. else {
  32239. switch (fillMode) {
  32240. case BABYLON.Material.PointFillMode:
  32241. indexToBind = null;
  32242. break;
  32243. case BABYLON.Material.WireFrameFillMode:
  32244. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32245. break;
  32246. default:
  32247. case BABYLON.Material.TriangleFillMode:
  32248. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32249. break;
  32250. }
  32251. }
  32252. // VBOs
  32253. this._geometry._bind(effect, indexToBind);
  32254. return this;
  32255. };
  32256. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32257. if (alternate === void 0) { alternate = false; }
  32258. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32259. return this;
  32260. }
  32261. this.onBeforeDrawObservable.notifyObservers(this);
  32262. var scene = this.getScene();
  32263. var engine = scene.getEngine();
  32264. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32265. // or triangles as points
  32266. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32267. }
  32268. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32269. // Triangles as wireframe
  32270. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32271. }
  32272. else {
  32273. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32274. }
  32275. if (scene._isAlternateRenderingEnabled && !alternate) {
  32276. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32277. if (!effect || !scene.activeCamera) {
  32278. return this;
  32279. }
  32280. scene._switchToAlternateCameraConfiguration(true);
  32281. this._effectiveMaterial.bindView(effect);
  32282. this._effectiveMaterial.bindViewProjection(effect);
  32283. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32284. this._draw(subMesh, fillMode, instancesCount, true);
  32285. engine.setViewport(scene.activeCamera.viewport);
  32286. scene._switchToAlternateCameraConfiguration(false);
  32287. this._effectiveMaterial.bindView(effect);
  32288. this._effectiveMaterial.bindViewProjection(effect);
  32289. }
  32290. return this;
  32291. };
  32292. /**
  32293. * Registers for this mesh a javascript function called just before the rendering process.
  32294. * This function is passed the current mesh.
  32295. * Return the Mesh.
  32296. */
  32297. Mesh.prototype.registerBeforeRender = function (func) {
  32298. this.onBeforeRenderObservable.add(func);
  32299. return this;
  32300. };
  32301. /**
  32302. * Disposes a previously registered javascript function called before the rendering.
  32303. * This function is passed the current mesh.
  32304. * Returns the Mesh.
  32305. */
  32306. Mesh.prototype.unregisterBeforeRender = function (func) {
  32307. this.onBeforeRenderObservable.removeCallback(func);
  32308. return this;
  32309. };
  32310. /**
  32311. * Registers for this mesh a javascript function called just after the rendering is complete.
  32312. * This function is passed the current mesh.
  32313. * Returns the Mesh.
  32314. */
  32315. Mesh.prototype.registerAfterRender = function (func) {
  32316. this.onAfterRenderObservable.add(func);
  32317. return this;
  32318. };
  32319. /**
  32320. * Disposes a previously registered javascript function called after the rendering.
  32321. * This function is passed the current mesh.
  32322. * Return the Mesh.
  32323. */
  32324. Mesh.prototype.unregisterAfterRender = function (func) {
  32325. this.onAfterRenderObservable.removeCallback(func);
  32326. return this;
  32327. };
  32328. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32329. var scene = this.getScene();
  32330. this._batchCache.mustReturn = false;
  32331. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32332. this._batchCache.visibleInstances[subMeshId] = null;
  32333. if (this._visibleInstances) {
  32334. var currentRenderId = scene.getRenderId();
  32335. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32336. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32337. var selfRenderId = this._renderId;
  32338. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32339. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32340. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32341. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32342. }
  32343. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32344. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32345. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32346. this._batchCache.mustReturn = true;
  32347. return this._batchCache;
  32348. }
  32349. if (currentRenderId !== selfRenderId) {
  32350. this._batchCache.renderSelf[subMeshId] = false;
  32351. }
  32352. }
  32353. this._renderIdForInstances[subMeshId] = currentRenderId;
  32354. }
  32355. return this._batchCache;
  32356. };
  32357. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32358. var visibleInstances = batch.visibleInstances[subMesh._id];
  32359. if (!visibleInstances) {
  32360. return this;
  32361. }
  32362. var matricesCount = visibleInstances.length + 1;
  32363. var bufferSize = matricesCount * 16 * 4;
  32364. var currentInstancesBufferSize = this._instancesBufferSize;
  32365. var instancesBuffer = this._instancesBuffer;
  32366. while (this._instancesBufferSize < bufferSize) {
  32367. this._instancesBufferSize *= 2;
  32368. }
  32369. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32370. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32371. }
  32372. var offset = 0;
  32373. var instancesCount = 0;
  32374. var world = this.getWorldMatrix();
  32375. if (batch.renderSelf[subMesh._id]) {
  32376. world.copyToArray(this._instancesData, offset);
  32377. offset += 16;
  32378. instancesCount++;
  32379. }
  32380. if (visibleInstances) {
  32381. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32382. var instance = visibleInstances[instanceIndex];
  32383. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32384. offset += 16;
  32385. instancesCount++;
  32386. }
  32387. }
  32388. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32389. if (instancesBuffer) {
  32390. instancesBuffer.dispose();
  32391. }
  32392. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32393. this._instancesBuffer = instancesBuffer;
  32394. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32395. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32396. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32397. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32398. }
  32399. else {
  32400. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32401. }
  32402. this._bind(subMesh, effect, fillMode);
  32403. this._draw(subMesh, fillMode, instancesCount);
  32404. engine.unbindInstanceAttributes();
  32405. return this;
  32406. };
  32407. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32408. var scene = this.getScene();
  32409. var engine = scene.getEngine();
  32410. if (hardwareInstancedRendering) {
  32411. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32412. }
  32413. else {
  32414. if (batch.renderSelf[subMesh._id]) {
  32415. // Draw
  32416. if (onBeforeDraw) {
  32417. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32418. }
  32419. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32420. }
  32421. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32422. if (visibleInstancesForSubMesh) {
  32423. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32424. var instance = visibleInstancesForSubMesh[instanceIndex];
  32425. // World
  32426. var world = instance.getWorldMatrix();
  32427. if (onBeforeDraw) {
  32428. onBeforeDraw(true, world, effectiveMaterial);
  32429. }
  32430. // Draw
  32431. this._draw(subMesh, fillMode);
  32432. }
  32433. }
  32434. }
  32435. return this;
  32436. };
  32437. /**
  32438. * Triggers the draw call for the mesh.
  32439. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32440. * Returns the Mesh.
  32441. */
  32442. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32443. this._checkOcclusionQuery();
  32444. if (this._isOccluded) {
  32445. return this;
  32446. }
  32447. var scene = this.getScene();
  32448. // Managing instances
  32449. var batch = this._getInstancesRenderList(subMesh._id);
  32450. if (batch.mustReturn) {
  32451. return this;
  32452. }
  32453. // Checking geometry state
  32454. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32455. return this;
  32456. }
  32457. this.onBeforeRenderObservable.notifyObservers(this);
  32458. var engine = scene.getEngine();
  32459. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32460. // Material
  32461. var material = subMesh.getMaterial();
  32462. if (!material) {
  32463. return this;
  32464. }
  32465. this._effectiveMaterial = material;
  32466. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32467. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32468. return this;
  32469. }
  32470. }
  32471. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32472. return this;
  32473. }
  32474. // Alpha mode
  32475. if (enableAlphaMode) {
  32476. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32477. }
  32478. // Outline - step 1
  32479. var savedDepthWrite = engine.getDepthWrite();
  32480. if (this.renderOutline) {
  32481. engine.setDepthWrite(false);
  32482. scene.getOutlineRenderer().render(subMesh, batch);
  32483. engine.setDepthWrite(savedDepthWrite);
  32484. }
  32485. var effect;
  32486. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32487. effect = subMesh.effect;
  32488. }
  32489. else {
  32490. effect = this._effectiveMaterial.getEffect();
  32491. }
  32492. if (!effect) {
  32493. return this;
  32494. }
  32495. var sideOrientation = this.overrideMaterialSideOrientation;
  32496. if (sideOrientation == null) {
  32497. sideOrientation = this._effectiveMaterial.sideOrientation;
  32498. if (this._getWorldMatrixDeterminant() < 0) {
  32499. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32500. }
  32501. }
  32502. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32503. if (this._effectiveMaterial.forceDepthWrite) {
  32504. engine.setDepthWrite(true);
  32505. }
  32506. // Bind
  32507. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32508. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32509. this._bind(subMesh, effect, fillMode);
  32510. }
  32511. var world = this.getWorldMatrix();
  32512. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32513. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32514. }
  32515. else {
  32516. this._effectiveMaterial.bind(world, this);
  32517. }
  32518. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32519. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32520. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32521. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32522. }
  32523. // Draw
  32524. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32525. // Unbind
  32526. this._effectiveMaterial.unbind();
  32527. // Outline - step 2
  32528. if (this.renderOutline && savedDepthWrite) {
  32529. engine.setDepthWrite(true);
  32530. engine.setColorWrite(false);
  32531. scene.getOutlineRenderer().render(subMesh, batch);
  32532. engine.setColorWrite(true);
  32533. }
  32534. // Overlay
  32535. if (this.renderOverlay) {
  32536. var currentMode = engine.getAlphaMode();
  32537. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32538. scene.getOutlineRenderer().render(subMesh, batch, true);
  32539. engine.setAlphaMode(currentMode);
  32540. }
  32541. this.onAfterRenderObservable.notifyObservers(this);
  32542. return this;
  32543. };
  32544. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32545. if (isInstance && effectiveMaterial) {
  32546. effectiveMaterial.bindOnlyWorldMatrix(world);
  32547. }
  32548. };
  32549. /**
  32550. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32551. */
  32552. Mesh.prototype.getEmittedParticleSystems = function () {
  32553. var results = new Array();
  32554. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32555. var particleSystem = this.getScene().particleSystems[index];
  32556. if (particleSystem.emitter === this) {
  32557. results.push(particleSystem);
  32558. }
  32559. }
  32560. return results;
  32561. };
  32562. /**
  32563. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32564. */
  32565. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32566. var results = new Array();
  32567. var descendants = this.getDescendants();
  32568. descendants.push(this);
  32569. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32570. var particleSystem = this.getScene().particleSystems[index];
  32571. var emitter = particleSystem.emitter;
  32572. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32573. results.push(particleSystem);
  32574. }
  32575. }
  32576. return results;
  32577. };
  32578. /**
  32579. * Normalize matrix weights so that all vertices have a total weight set to 1
  32580. */
  32581. Mesh.prototype.cleanMatrixWeights = function () {
  32582. var epsilon = 1e-3;
  32583. var noInfluenceBoneIndex = 0.0;
  32584. if (this.skeleton) {
  32585. noInfluenceBoneIndex = this.skeleton.bones.length;
  32586. }
  32587. else {
  32588. return;
  32589. }
  32590. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32591. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32592. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32593. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32594. var influencers = this.numBoneInfluencers;
  32595. var size = matricesWeights.length;
  32596. for (var i = 0; i < size; i += 4) {
  32597. var weight = 0.0;
  32598. var firstZeroWeight = -1;
  32599. for (var j = 0; j < 4; j++) {
  32600. var w = matricesWeights[i + j];
  32601. weight += w;
  32602. if (w < epsilon && firstZeroWeight < 0) {
  32603. firstZeroWeight = j;
  32604. }
  32605. }
  32606. if (matricesWeightsExtra) {
  32607. for (var j = 0; j < 4; j++) {
  32608. var w = matricesWeightsExtra[i + j];
  32609. weight += w;
  32610. if (w < epsilon && firstZeroWeight < 0) {
  32611. firstZeroWeight = j + 4;
  32612. }
  32613. }
  32614. }
  32615. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32616. firstZeroWeight = influencers - 1;
  32617. }
  32618. if (weight > epsilon) {
  32619. var mweight = 1.0 / weight;
  32620. for (var j = 0; j < 4; j++) {
  32621. matricesWeights[i + j] *= mweight;
  32622. }
  32623. if (matricesWeightsExtra) {
  32624. for (var j = 0; j < 4; j++) {
  32625. matricesWeightsExtra[i + j] *= mweight;
  32626. }
  32627. }
  32628. }
  32629. else {
  32630. if (firstZeroWeight >= 4) {
  32631. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32632. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32633. }
  32634. else {
  32635. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32636. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32637. }
  32638. }
  32639. }
  32640. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32641. if (matricesIndicesExtra) {
  32642. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32643. }
  32644. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32645. if (matricesWeightsExtra) {
  32646. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32647. }
  32648. };
  32649. Mesh.prototype._checkDelayState = function () {
  32650. var scene = this.getScene();
  32651. if (this._geometry) {
  32652. this._geometry.load(scene);
  32653. }
  32654. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32655. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32656. this._queueLoad(scene);
  32657. }
  32658. return this;
  32659. };
  32660. Mesh.prototype._queueLoad = function (scene) {
  32661. var _this = this;
  32662. scene._addPendingData(this);
  32663. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32664. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32665. if (data instanceof ArrayBuffer) {
  32666. _this._delayLoadingFunction(data, _this);
  32667. }
  32668. else {
  32669. _this._delayLoadingFunction(JSON.parse(data), _this);
  32670. }
  32671. _this.instances.forEach(function (instance) {
  32672. instance._syncSubMeshes();
  32673. });
  32674. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32675. scene._removePendingData(_this);
  32676. }, function () { }, scene.database, getBinaryData);
  32677. return this;
  32678. };
  32679. /**
  32680. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32681. */
  32682. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32683. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32684. return false;
  32685. }
  32686. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32687. return false;
  32688. }
  32689. this._checkDelayState();
  32690. return true;
  32691. };
  32692. /**
  32693. * Sets the mesh material by the material or multiMaterial `id` property.
  32694. * The material `id` is a string identifying the material or the multiMaterial.
  32695. * This method returns the Mesh.
  32696. */
  32697. Mesh.prototype.setMaterialByID = function (id) {
  32698. var materials = this.getScene().materials;
  32699. var index;
  32700. for (index = materials.length - 1; index > -1; index--) {
  32701. if (materials[index].id === id) {
  32702. this.material = materials[index];
  32703. return this;
  32704. }
  32705. }
  32706. // Multi
  32707. var multiMaterials = this.getScene().multiMaterials;
  32708. for (index = multiMaterials.length - 1; index > -1; index--) {
  32709. if (multiMaterials[index].id === id) {
  32710. this.material = multiMaterials[index];
  32711. return this;
  32712. }
  32713. }
  32714. return this;
  32715. };
  32716. /**
  32717. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32718. */
  32719. Mesh.prototype.getAnimatables = function () {
  32720. var results = new Array();
  32721. if (this.material) {
  32722. results.push(this.material);
  32723. }
  32724. if (this.skeleton) {
  32725. results.push(this.skeleton);
  32726. }
  32727. return results;
  32728. };
  32729. /**
  32730. * Modifies the mesh geometry according to the passed transformation matrix.
  32731. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32732. * The mesh normals are modified accordingly the same transformation.
  32733. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32734. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32735. * Returns the Mesh.
  32736. */
  32737. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32738. // Position
  32739. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32740. return this;
  32741. }
  32742. var submeshes = this.subMeshes.splice(0);
  32743. this._resetPointsArrayCache();
  32744. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32745. var temp = new Array();
  32746. var index;
  32747. for (index = 0; index < data.length; index += 3) {
  32748. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32749. }
  32750. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32751. // Normals
  32752. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32753. return this;
  32754. }
  32755. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32756. temp = [];
  32757. for (index = 0; index < data.length; index += 3) {
  32758. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32759. }
  32760. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32761. // flip faces?
  32762. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32763. this.flipFaces();
  32764. }
  32765. // Restore submeshes
  32766. this.releaseSubMeshes();
  32767. this.subMeshes = submeshes;
  32768. return this;
  32769. };
  32770. /**
  32771. * Modifies the mesh geometry according to its own current World Matrix.
  32772. * The mesh World Matrix is then reset.
  32773. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32774. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32775. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32776. * Returns the Mesh.
  32777. */
  32778. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32779. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32780. this.scaling.copyFromFloats(1, 1, 1);
  32781. this.position.copyFromFloats(0, 0, 0);
  32782. this.rotation.copyFromFloats(0, 0, 0);
  32783. //only if quaternion is already set
  32784. if (this.rotationQuaternion) {
  32785. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32786. }
  32787. this._worldMatrix = BABYLON.Matrix.Identity();
  32788. return this;
  32789. };
  32790. Object.defineProperty(Mesh.prototype, "_positions", {
  32791. // Cache
  32792. get: function () {
  32793. if (this._geometry) {
  32794. return this._geometry._positions;
  32795. }
  32796. return null;
  32797. },
  32798. enumerable: true,
  32799. configurable: true
  32800. });
  32801. Mesh.prototype._resetPointsArrayCache = function () {
  32802. if (this._geometry) {
  32803. this._geometry._resetPointsArrayCache();
  32804. }
  32805. return this;
  32806. };
  32807. Mesh.prototype._generatePointsArray = function () {
  32808. if (this._geometry) {
  32809. return this._geometry._generatePointsArray();
  32810. }
  32811. return false;
  32812. };
  32813. /**
  32814. * Returns a new Mesh object generated from the current mesh properties.
  32815. * This method must not get confused with createInstance().
  32816. * The parameter `name` is a string, the name given to the new mesh.
  32817. * The optional parameter `newParent` can be any Node object (default `null`).
  32818. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32819. * 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.
  32820. */
  32821. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32822. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32823. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32824. };
  32825. /**
  32826. * Releases resources associated with this mesh.
  32827. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32828. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32829. */
  32830. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32831. var _this = this;
  32832. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32833. this.morphTargetManager = null;
  32834. if (this._geometry) {
  32835. this._geometry.releaseForMesh(this, true);
  32836. }
  32837. // Sources
  32838. var meshes = this.getScene().meshes;
  32839. meshes.forEach(function (abstractMesh) {
  32840. var mesh = abstractMesh;
  32841. if (mesh._source && mesh._source === _this) {
  32842. mesh._source = null;
  32843. }
  32844. });
  32845. this._source = null;
  32846. // Instances
  32847. if (this._instancesBuffer) {
  32848. this._instancesBuffer.dispose();
  32849. this._instancesBuffer = null;
  32850. }
  32851. while (this.instances.length) {
  32852. this.instances[0].dispose();
  32853. }
  32854. // Effect layers.
  32855. var effectLayers = this.getScene().effectLayers;
  32856. for (var i = 0; i < effectLayers.length; i++) {
  32857. var effectLayer = effectLayers[i];
  32858. if (effectLayer) {
  32859. effectLayer._disposeMesh(this);
  32860. }
  32861. }
  32862. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32863. };
  32864. /**
  32865. * Modifies the mesh geometry according to a displacement map.
  32866. * 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.
  32867. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32868. * This method returns nothing.
  32869. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32870. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32871. * 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.
  32872. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32873. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32874. *
  32875. * Returns the Mesh.
  32876. */
  32877. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32878. var _this = this;
  32879. var scene = this.getScene();
  32880. var onload = function (img) {
  32881. // Getting height map data
  32882. var canvas = document.createElement("canvas");
  32883. var context = canvas.getContext("2d");
  32884. var heightMapWidth = img.width;
  32885. var heightMapHeight = img.height;
  32886. canvas.width = heightMapWidth;
  32887. canvas.height = heightMapHeight;
  32888. context.drawImage(img, 0, 0);
  32889. // Create VertexData from map data
  32890. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32891. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32892. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32893. //execute success callback, if set
  32894. if (onSuccess) {
  32895. onSuccess(_this);
  32896. }
  32897. };
  32898. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32899. return this;
  32900. };
  32901. /**
  32902. * Modifies the mesh geometry according to a displacementMap buffer.
  32903. * 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.
  32904. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32905. * This method returns nothing.
  32906. * 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.
  32907. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32908. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32909. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32910. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32911. *
  32912. * Returns the Mesh.
  32913. */
  32914. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32915. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32916. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32917. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32918. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32919. return this;
  32920. }
  32921. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32922. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32923. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32924. var position = BABYLON.Vector3.Zero();
  32925. var normal = BABYLON.Vector3.Zero();
  32926. var uv = BABYLON.Vector2.Zero();
  32927. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32928. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32929. for (var index = 0; index < positions.length; index += 3) {
  32930. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32931. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32932. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32933. // Compute height
  32934. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32935. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32936. var pos = (u + v * heightMapWidth) * 4;
  32937. var r = buffer[pos] / 255.0;
  32938. var g = buffer[pos + 1] / 255.0;
  32939. var b = buffer[pos + 2] / 255.0;
  32940. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32941. normal.normalize();
  32942. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32943. position = position.add(normal);
  32944. position.toArray(positions, index);
  32945. }
  32946. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32947. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32948. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32949. return this;
  32950. };
  32951. /**
  32952. * Modify the mesh to get a flat shading rendering.
  32953. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32954. * This method returns the Mesh.
  32955. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32956. */
  32957. Mesh.prototype.convertToFlatShadedMesh = function () {
  32958. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32959. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32960. var kinds = this.getVerticesDataKinds();
  32961. var vbs = {};
  32962. var data = {};
  32963. var newdata = {};
  32964. var updatableNormals = false;
  32965. var kindIndex;
  32966. var kind;
  32967. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32968. kind = kinds[kindIndex];
  32969. var vertexBuffer = this.getVertexBuffer(kind);
  32970. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32971. updatableNormals = vertexBuffer.isUpdatable();
  32972. kinds.splice(kindIndex, 1);
  32973. kindIndex--;
  32974. continue;
  32975. }
  32976. vbs[kind] = vertexBuffer;
  32977. data[kind] = vbs[kind].getData();
  32978. newdata[kind] = [];
  32979. }
  32980. // Save previous submeshes
  32981. var previousSubmeshes = this.subMeshes.slice(0);
  32982. var indices = this.getIndices();
  32983. var totalIndices = this.getTotalIndices();
  32984. // Generating unique vertices per face
  32985. var index;
  32986. for (index = 0; index < totalIndices; index++) {
  32987. var vertexIndex = indices[index];
  32988. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32989. kind = kinds[kindIndex];
  32990. var stride = vbs[kind].getStrideSize();
  32991. for (var offset = 0; offset < stride; offset++) {
  32992. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32993. }
  32994. }
  32995. }
  32996. // Updating faces & normal
  32997. var normals = [];
  32998. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32999. for (index = 0; index < totalIndices; index += 3) {
  33000. indices[index] = index;
  33001. indices[index + 1] = index + 1;
  33002. indices[index + 2] = index + 2;
  33003. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33004. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33005. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33006. var p1p2 = p1.subtract(p2);
  33007. var p3p2 = p3.subtract(p2);
  33008. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33009. // Store same normals for every vertex
  33010. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33011. normals.push(normal.x);
  33012. normals.push(normal.y);
  33013. normals.push(normal.z);
  33014. }
  33015. }
  33016. this.setIndices(indices);
  33017. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33018. // Updating vertex buffers
  33019. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33020. kind = kinds[kindIndex];
  33021. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33022. }
  33023. // Updating submeshes
  33024. this.releaseSubMeshes();
  33025. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33026. var previousOne = previousSubmeshes[submeshIndex];
  33027. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33028. }
  33029. this.synchronizeInstances();
  33030. return this;
  33031. };
  33032. /**
  33033. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33034. * In other words, more vertices, no more indices and a single bigger VBO.
  33035. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33036. * Returns the Mesh.
  33037. */
  33038. Mesh.prototype.convertToUnIndexedMesh = function () {
  33039. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33040. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33041. var kinds = this.getVerticesDataKinds();
  33042. var vbs = {};
  33043. var data = {};
  33044. var newdata = {};
  33045. var kindIndex;
  33046. var kind;
  33047. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33048. kind = kinds[kindIndex];
  33049. var vertexBuffer = this.getVertexBuffer(kind);
  33050. vbs[kind] = vertexBuffer;
  33051. data[kind] = vbs[kind].getData();
  33052. newdata[kind] = [];
  33053. }
  33054. // Save previous submeshes
  33055. var previousSubmeshes = this.subMeshes.slice(0);
  33056. var indices = this.getIndices();
  33057. var totalIndices = this.getTotalIndices();
  33058. // Generating unique vertices per face
  33059. var index;
  33060. for (index = 0; index < totalIndices; index++) {
  33061. var vertexIndex = indices[index];
  33062. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33063. kind = kinds[kindIndex];
  33064. var stride = vbs[kind].getStrideSize();
  33065. for (var offset = 0; offset < stride; offset++) {
  33066. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33067. }
  33068. }
  33069. }
  33070. // Updating indices
  33071. for (index = 0; index < totalIndices; index += 3) {
  33072. indices[index] = index;
  33073. indices[index + 1] = index + 1;
  33074. indices[index + 2] = index + 2;
  33075. }
  33076. this.setIndices(indices);
  33077. // Updating vertex buffers
  33078. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33079. kind = kinds[kindIndex];
  33080. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33081. }
  33082. // Updating submeshes
  33083. this.releaseSubMeshes();
  33084. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33085. var previousOne = previousSubmeshes[submeshIndex];
  33086. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33087. }
  33088. this._unIndexed = true;
  33089. this.synchronizeInstances();
  33090. return this;
  33091. };
  33092. /**
  33093. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33094. * This method returns the Mesh.
  33095. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33096. */
  33097. Mesh.prototype.flipFaces = function (flipNormals) {
  33098. if (flipNormals === void 0) { flipNormals = false; }
  33099. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33100. var i;
  33101. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33102. for (i = 0; i < vertex_data.normals.length; i++) {
  33103. vertex_data.normals[i] *= -1;
  33104. }
  33105. }
  33106. if (vertex_data.indices) {
  33107. var temp;
  33108. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33109. // reassign indices
  33110. temp = vertex_data.indices[i + 1];
  33111. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33112. vertex_data.indices[i + 2] = temp;
  33113. }
  33114. }
  33115. vertex_data.applyToMesh(this);
  33116. return this;
  33117. };
  33118. // Instances
  33119. /**
  33120. * Creates a new InstancedMesh object from the mesh model.
  33121. * An instance shares the same properties and the same material than its model.
  33122. * Only these properties of each instance can then be set individually :
  33123. * - position
  33124. * - rotation
  33125. * - rotationQuaternion
  33126. * - setPivotMatrix
  33127. * - scaling
  33128. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33129. * Warning : this method is not supported for Line mesh and LineSystem
  33130. */
  33131. Mesh.prototype.createInstance = function (name) {
  33132. return new BABYLON.InstancedMesh(name, this);
  33133. };
  33134. /**
  33135. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33136. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33137. * This method returns the Mesh.
  33138. */
  33139. Mesh.prototype.synchronizeInstances = function () {
  33140. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33141. var instance = this.instances[instanceIndex];
  33142. instance._syncSubMeshes();
  33143. }
  33144. return this;
  33145. };
  33146. /**
  33147. * Simplify the mesh according to the given array of settings.
  33148. * Function will return immediately and will simplify async. It returns the Mesh.
  33149. * @param settings a collection of simplification settings.
  33150. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33151. * @param type the type of simplification to run.
  33152. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33153. */
  33154. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33155. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33156. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33157. this.getScene().simplificationQueue.addTask({
  33158. settings: settings,
  33159. parallelProcessing: parallelProcessing,
  33160. mesh: this,
  33161. simplificationType: simplificationType,
  33162. successCallback: successCallback
  33163. });
  33164. return this;
  33165. };
  33166. /**
  33167. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33168. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33169. * This should be used together with the simplification to avoid disappearing triangles.
  33170. * Returns the Mesh.
  33171. * @param successCallback an optional success callback to be called after the optimization finished.
  33172. */
  33173. Mesh.prototype.optimizeIndices = function (successCallback) {
  33174. var _this = this;
  33175. var indices = this.getIndices();
  33176. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33177. if (!positions || !indices) {
  33178. return this;
  33179. }
  33180. var vectorPositions = new Array();
  33181. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33182. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33183. }
  33184. var dupes = new Array();
  33185. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33186. var realPos = vectorPositions.length - 1 - iteration;
  33187. var testedPosition = vectorPositions[realPos];
  33188. for (var j = 0; j < realPos; ++j) {
  33189. var againstPosition = vectorPositions[j];
  33190. if (testedPosition.equals(againstPosition)) {
  33191. dupes[realPos] = j;
  33192. break;
  33193. }
  33194. }
  33195. }, function () {
  33196. for (var i = 0; i < indices.length; ++i) {
  33197. indices[i] = dupes[indices[i]] || indices[i];
  33198. }
  33199. //indices are now reordered
  33200. var originalSubMeshes = _this.subMeshes.slice(0);
  33201. _this.setIndices(indices);
  33202. _this.subMeshes = originalSubMeshes;
  33203. if (successCallback) {
  33204. successCallback(_this);
  33205. }
  33206. });
  33207. return this;
  33208. };
  33209. Mesh.prototype.serialize = function (serializationObject) {
  33210. serializationObject.name = this.name;
  33211. serializationObject.id = this.id;
  33212. serializationObject.type = this.getClassName();
  33213. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33214. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33215. }
  33216. serializationObject.position = this.position.asArray();
  33217. if (this.rotationQuaternion) {
  33218. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33219. }
  33220. else if (this.rotation) {
  33221. serializationObject.rotation = this.rotation.asArray();
  33222. }
  33223. serializationObject.scaling = this.scaling.asArray();
  33224. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33225. serializationObject.isEnabled = this.isEnabled(false);
  33226. serializationObject.isVisible = this.isVisible;
  33227. serializationObject.infiniteDistance = this.infiniteDistance;
  33228. serializationObject.pickable = this.isPickable;
  33229. serializationObject.receiveShadows = this.receiveShadows;
  33230. serializationObject.billboardMode = this.billboardMode;
  33231. serializationObject.visibility = this.visibility;
  33232. serializationObject.checkCollisions = this.checkCollisions;
  33233. serializationObject.isBlocker = this.isBlocker;
  33234. // Parent
  33235. if (this.parent) {
  33236. serializationObject.parentId = this.parent.id;
  33237. }
  33238. // Geometry
  33239. serializationObject.isUnIndexed = this.isUnIndexed;
  33240. var geometry = this._geometry;
  33241. if (geometry) {
  33242. var geometryId = geometry.id;
  33243. serializationObject.geometryId = geometryId;
  33244. // SubMeshes
  33245. serializationObject.subMeshes = [];
  33246. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33247. var subMesh = this.subMeshes[subIndex];
  33248. serializationObject.subMeshes.push({
  33249. materialIndex: subMesh.materialIndex,
  33250. verticesStart: subMesh.verticesStart,
  33251. verticesCount: subMesh.verticesCount,
  33252. indexStart: subMesh.indexStart,
  33253. indexCount: subMesh.indexCount
  33254. });
  33255. }
  33256. }
  33257. // Material
  33258. if (this.material) {
  33259. serializationObject.materialId = this.material.id;
  33260. }
  33261. else {
  33262. this.material = null;
  33263. }
  33264. // Morph targets
  33265. if (this.morphTargetManager) {
  33266. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33267. }
  33268. // Skeleton
  33269. if (this.skeleton) {
  33270. serializationObject.skeletonId = this.skeleton.id;
  33271. }
  33272. // Physics
  33273. //TODO implement correct serialization for physics impostors.
  33274. var impostor = this.getPhysicsImpostor();
  33275. if (impostor) {
  33276. serializationObject.physicsMass = impostor.getParam("mass");
  33277. serializationObject.physicsFriction = impostor.getParam("friction");
  33278. serializationObject.physicsRestitution = impostor.getParam("mass");
  33279. serializationObject.physicsImpostor = impostor.type;
  33280. }
  33281. // Metadata
  33282. if (this.metadata) {
  33283. serializationObject.metadata = this.metadata;
  33284. }
  33285. // Instances
  33286. serializationObject.instances = [];
  33287. for (var index = 0; index < this.instances.length; index++) {
  33288. var instance = this.instances[index];
  33289. var serializationInstance = {
  33290. name: instance.name,
  33291. id: instance.id,
  33292. position: instance.position.asArray(),
  33293. scaling: instance.scaling.asArray()
  33294. };
  33295. if (instance.rotationQuaternion) {
  33296. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33297. }
  33298. else if (instance.rotation) {
  33299. serializationInstance.rotation = instance.rotation.asArray();
  33300. }
  33301. serializationObject.instances.push(serializationInstance);
  33302. // Animations
  33303. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33304. serializationInstance.ranges = instance.serializeAnimationRanges();
  33305. }
  33306. //
  33307. // Animations
  33308. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33309. serializationObject.ranges = this.serializeAnimationRanges();
  33310. // Layer mask
  33311. serializationObject.layerMask = this.layerMask;
  33312. // Alpha
  33313. serializationObject.alphaIndex = this.alphaIndex;
  33314. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33315. // Overlay
  33316. serializationObject.overlayAlpha = this.overlayAlpha;
  33317. serializationObject.overlayColor = this.overlayColor.asArray();
  33318. serializationObject.renderOverlay = this.renderOverlay;
  33319. // Fog
  33320. serializationObject.applyFog = this.applyFog;
  33321. // Action Manager
  33322. if (this.actionManager) {
  33323. serializationObject.actions = this.actionManager.serialize(this.name);
  33324. }
  33325. };
  33326. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33327. if (!this.geometry) {
  33328. return;
  33329. }
  33330. this._markSubMeshesAsAttributesDirty();
  33331. var morphTargetManager = this._morphTargetManager;
  33332. if (morphTargetManager && morphTargetManager.vertexCount) {
  33333. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33334. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33335. this.morphTargetManager = null;
  33336. return;
  33337. }
  33338. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33339. var morphTarget = morphTargetManager.getActiveTarget(index);
  33340. var positions = morphTarget.getPositions();
  33341. if (!positions) {
  33342. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33343. return;
  33344. }
  33345. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33346. var normals = morphTarget.getNormals();
  33347. if (normals) {
  33348. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33349. }
  33350. var tangents = morphTarget.getTangents();
  33351. if (tangents) {
  33352. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33353. }
  33354. }
  33355. }
  33356. else {
  33357. var index = 0;
  33358. // Positions
  33359. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33360. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33361. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33362. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33363. }
  33364. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33365. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33366. }
  33367. index++;
  33368. }
  33369. }
  33370. };
  33371. // Statics
  33372. /**
  33373. * Returns a new Mesh object parsed from the source provided.
  33374. * The parameter `parsedMesh` is the source.
  33375. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33376. */
  33377. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33378. var mesh;
  33379. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33380. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33381. }
  33382. else {
  33383. mesh = new Mesh(parsedMesh.name, scene);
  33384. }
  33385. mesh.id = parsedMesh.id;
  33386. if (BABYLON.Tags) {
  33387. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33388. }
  33389. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33390. if (parsedMesh.metadata !== undefined) {
  33391. mesh.metadata = parsedMesh.metadata;
  33392. }
  33393. if (parsedMesh.rotationQuaternion) {
  33394. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33395. }
  33396. else if (parsedMesh.rotation) {
  33397. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33398. }
  33399. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33400. if (parsedMesh.localMatrix) {
  33401. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33402. }
  33403. else if (parsedMesh.pivotMatrix) {
  33404. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33405. }
  33406. mesh.setEnabled(parsedMesh.isEnabled);
  33407. mesh.isVisible = parsedMesh.isVisible;
  33408. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33409. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33410. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33411. if (parsedMesh.applyFog !== undefined) {
  33412. mesh.applyFog = parsedMesh.applyFog;
  33413. }
  33414. if (parsedMesh.pickable !== undefined) {
  33415. mesh.isPickable = parsedMesh.pickable;
  33416. }
  33417. if (parsedMesh.alphaIndex !== undefined) {
  33418. mesh.alphaIndex = parsedMesh.alphaIndex;
  33419. }
  33420. mesh.receiveShadows = parsedMesh.receiveShadows;
  33421. mesh.billboardMode = parsedMesh.billboardMode;
  33422. if (parsedMesh.visibility !== undefined) {
  33423. mesh.visibility = parsedMesh.visibility;
  33424. }
  33425. mesh.checkCollisions = parsedMesh.checkCollisions;
  33426. if (parsedMesh.isBlocker !== undefined) {
  33427. mesh.isBlocker = parsedMesh.isBlocker;
  33428. }
  33429. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33430. // freezeWorldMatrix
  33431. if (parsedMesh.freezeWorldMatrix) {
  33432. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33433. }
  33434. // Parent
  33435. if (parsedMesh.parentId) {
  33436. mesh._waitingParentId = parsedMesh.parentId;
  33437. }
  33438. // Actions
  33439. if (parsedMesh.actions !== undefined) {
  33440. mesh._waitingActions = parsedMesh.actions;
  33441. }
  33442. // Overlay
  33443. if (parsedMesh.overlayAlpha !== undefined) {
  33444. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33445. }
  33446. if (parsedMesh.overlayColor !== undefined) {
  33447. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33448. }
  33449. if (parsedMesh.renderOverlay !== undefined) {
  33450. mesh.renderOverlay = parsedMesh.renderOverlay;
  33451. }
  33452. // Geometry
  33453. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33454. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33455. if (parsedMesh.delayLoadingFile) {
  33456. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33457. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33458. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33459. if (parsedMesh._binaryInfo) {
  33460. mesh._binaryInfo = parsedMesh._binaryInfo;
  33461. }
  33462. mesh._delayInfo = [];
  33463. if (parsedMesh.hasUVs) {
  33464. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33465. }
  33466. if (parsedMesh.hasUVs2) {
  33467. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33468. }
  33469. if (parsedMesh.hasUVs3) {
  33470. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33471. }
  33472. if (parsedMesh.hasUVs4) {
  33473. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33474. }
  33475. if (parsedMesh.hasUVs5) {
  33476. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33477. }
  33478. if (parsedMesh.hasUVs6) {
  33479. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33480. }
  33481. if (parsedMesh.hasColors) {
  33482. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33483. }
  33484. if (parsedMesh.hasMatricesIndices) {
  33485. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33486. }
  33487. if (parsedMesh.hasMatricesWeights) {
  33488. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33489. }
  33490. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33491. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33492. mesh._checkDelayState();
  33493. }
  33494. }
  33495. else {
  33496. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33497. }
  33498. // Material
  33499. if (parsedMesh.materialId) {
  33500. mesh.setMaterialByID(parsedMesh.materialId);
  33501. }
  33502. else {
  33503. mesh.material = null;
  33504. }
  33505. // Morph targets
  33506. if (parsedMesh.morphTargetManagerId > -1) {
  33507. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33508. }
  33509. // Skeleton
  33510. if (parsedMesh.skeletonId > -1) {
  33511. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33512. if (parsedMesh.numBoneInfluencers) {
  33513. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33514. }
  33515. }
  33516. // Animations
  33517. if (parsedMesh.animations) {
  33518. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33519. var parsedAnimation = parsedMesh.animations[animationIndex];
  33520. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33521. }
  33522. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33523. }
  33524. if (parsedMesh.autoAnimate) {
  33525. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33526. }
  33527. // Layer Mask
  33528. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33529. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33530. }
  33531. else {
  33532. mesh.layerMask = 0x0FFFFFFF;
  33533. }
  33534. // Physics
  33535. if (parsedMesh.physicsImpostor) {
  33536. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33537. mass: parsedMesh.physicsMass,
  33538. friction: parsedMesh.physicsFriction,
  33539. restitution: parsedMesh.physicsRestitution
  33540. }, scene);
  33541. }
  33542. // Instances
  33543. if (parsedMesh.instances) {
  33544. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33545. var parsedInstance = parsedMesh.instances[index];
  33546. var instance = mesh.createInstance(parsedInstance.name);
  33547. if (parsedInstance.id) {
  33548. instance.id = parsedInstance.id;
  33549. }
  33550. if (BABYLON.Tags) {
  33551. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33552. }
  33553. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33554. if (parsedInstance.parentId) {
  33555. instance._waitingParentId = parsedInstance.parentId;
  33556. }
  33557. if (parsedInstance.rotationQuaternion) {
  33558. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33559. }
  33560. else if (parsedInstance.rotation) {
  33561. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33562. }
  33563. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33564. instance.checkCollisions = mesh.checkCollisions;
  33565. if (parsedMesh.animations) {
  33566. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33567. parsedAnimation = parsedMesh.animations[animationIndex];
  33568. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33569. }
  33570. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33571. }
  33572. }
  33573. }
  33574. return mesh;
  33575. };
  33576. /**
  33577. * Creates a ribbon mesh.
  33578. * Please consider using the same method from the MeshBuilder class instead.
  33579. * 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.
  33580. *
  33581. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33582. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33583. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33584. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33585. * 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.
  33586. * 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.
  33587. * 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
  33588. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33589. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33591. */
  33592. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33593. if (closeArray === void 0) { closeArray = false; }
  33594. if (updatable === void 0) { updatable = false; }
  33595. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33596. pathArray: pathArray,
  33597. closeArray: closeArray,
  33598. closePath: closePath,
  33599. offset: offset,
  33600. updatable: updatable,
  33601. sideOrientation: sideOrientation,
  33602. instance: instance
  33603. }, scene);
  33604. };
  33605. /**
  33606. * Creates a plane polygonal mesh. By default, this is a disc.
  33607. * Please consider using the same method from the MeshBuilder class instead.
  33608. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33609. * 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.
  33610. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33611. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33612. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33613. */
  33614. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33615. if (scene === void 0) { scene = null; }
  33616. var options = {
  33617. radius: radius,
  33618. tessellation: tessellation,
  33619. sideOrientation: sideOrientation,
  33620. updatable: updatable
  33621. };
  33622. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33623. };
  33624. /**
  33625. * Creates a box mesh.
  33626. * Please consider using the same method from the MeshBuilder class instead.
  33627. * The parameter `size` sets the size (float) of each box side (default 1).
  33628. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33629. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33630. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33631. */
  33632. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33633. if (scene === void 0) { scene = null; }
  33634. var options = {
  33635. size: size,
  33636. sideOrientation: sideOrientation,
  33637. updatable: updatable
  33638. };
  33639. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33640. };
  33641. /**
  33642. * Creates a sphere mesh.
  33643. * Please consider using the same method from the MeshBuilder class instead.
  33644. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33645. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33647. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33649. */
  33650. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33651. var options = {
  33652. segments: segments,
  33653. diameterX: diameter,
  33654. diameterY: diameter,
  33655. diameterZ: diameter,
  33656. sideOrientation: sideOrientation,
  33657. updatable: updatable
  33658. };
  33659. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33660. };
  33661. /**
  33662. * Creates a cylinder or a cone mesh.
  33663. * Please consider using the same method from the MeshBuilder class instead.
  33664. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33665. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33666. * 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.
  33667. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33668. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33669. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33670. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33672. */
  33673. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33674. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33675. if (scene !== undefined) {
  33676. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33677. updatable = scene;
  33678. }
  33679. scene = subdivisions;
  33680. subdivisions = 1;
  33681. }
  33682. var options = {
  33683. height: height,
  33684. diameterTop: diameterTop,
  33685. diameterBottom: diameterBottom,
  33686. tessellation: tessellation,
  33687. subdivisions: subdivisions,
  33688. sideOrientation: sideOrientation,
  33689. updatable: updatable
  33690. };
  33691. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33692. };
  33693. // Torus (Code from SharpDX.org)
  33694. /**
  33695. * Creates a torus mesh.
  33696. * Please consider using the same method from the MeshBuilder class instead.
  33697. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33698. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33699. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33700. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33701. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33703. */
  33704. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33705. var options = {
  33706. diameter: diameter,
  33707. thickness: thickness,
  33708. tessellation: tessellation,
  33709. sideOrientation: sideOrientation,
  33710. updatable: updatable
  33711. };
  33712. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33713. };
  33714. /**
  33715. * Creates a torus knot mesh.
  33716. * Please consider using the same method from the MeshBuilder class instead.
  33717. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33718. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33719. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33720. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33721. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33722. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33724. */
  33725. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33726. var options = {
  33727. radius: radius,
  33728. tube: tube,
  33729. radialSegments: radialSegments,
  33730. tubularSegments: tubularSegments,
  33731. p: p,
  33732. q: q,
  33733. sideOrientation: sideOrientation,
  33734. updatable: updatable
  33735. };
  33736. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33737. };
  33738. /**
  33739. * Creates a line mesh.
  33740. * Please consider using the same method from the MeshBuilder class instead.
  33741. * 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.
  33742. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33743. * The parameter `points` is an array successive Vector3.
  33744. * 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
  33745. * When updating an instance, remember that only point positions can change, not the number of points.
  33746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33747. */
  33748. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33749. if (scene === void 0) { scene = null; }
  33750. if (updatable === void 0) { updatable = false; }
  33751. if (instance === void 0) { instance = null; }
  33752. var options = {
  33753. points: points,
  33754. updatable: updatable,
  33755. instance: instance
  33756. };
  33757. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33758. };
  33759. /**
  33760. * Creates a dashed line mesh.
  33761. * Please consider using the same method from the MeshBuilder class instead.
  33762. * 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.
  33763. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33764. * The parameter `points` is an array successive Vector3.
  33765. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33766. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33767. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33768. * 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
  33769. * When updating an instance, remember that only point positions can change, not the number of points.
  33770. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33771. */
  33772. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33773. if (scene === void 0) { scene = null; }
  33774. var options = {
  33775. points: points,
  33776. dashSize: dashSize,
  33777. gapSize: gapSize,
  33778. dashNb: dashNb,
  33779. updatable: updatable,
  33780. instance: instance
  33781. };
  33782. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33783. };
  33784. /**
  33785. * Creates a polygon mesh.
  33786. * Please consider using the same method from the MeshBuilder class instead.
  33787. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33788. * 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.
  33789. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33790. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33791. * Remember you can only change the shape positions, not their number when updating a polygon.
  33792. */
  33793. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33794. var options = {
  33795. shape: shape,
  33796. holes: holes,
  33797. updatable: updatable,
  33798. sideOrientation: sideOrientation
  33799. };
  33800. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33801. };
  33802. /**
  33803. * Creates an extruded polygon mesh, with depth in the Y direction.
  33804. * Please consider using the same method from the MeshBuilder class instead.
  33805. */
  33806. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33807. var options = {
  33808. shape: shape,
  33809. holes: holes,
  33810. depth: depth,
  33811. updatable: updatable,
  33812. sideOrientation: sideOrientation
  33813. };
  33814. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33815. };
  33816. /**
  33817. * Creates an extruded shape mesh.
  33818. * 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.
  33819. * Please consider using the same method from the MeshBuilder class instead.
  33820. *
  33821. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33822. * 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
  33823. * extruded along the Z axis.
  33824. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33825. * 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.
  33826. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33827. * 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
  33828. * 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
  33829. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33830. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33831. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33833. */
  33834. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33835. if (scene === void 0) { scene = null; }
  33836. var options = {
  33837. shape: shape,
  33838. path: path,
  33839. scale: scale,
  33840. rotation: rotation,
  33841. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33842. sideOrientation: sideOrientation,
  33843. instance: instance,
  33844. updatable: updatable
  33845. };
  33846. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33847. };
  33848. /**
  33849. * Creates an custom extruded shape mesh.
  33850. * 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.
  33851. * Please consider using the same method from the MeshBuilder class instead.
  33852. *
  33853. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33854. * 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
  33855. * extruded along the Z axis.
  33856. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33857. * 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
  33858. * and the distance of this point from the begining of the path :
  33859. * ```javascript
  33860. * var rotationFunction = function(i, distance) {
  33861. * // do things
  33862. * return rotationValue; }
  33863. * ```
  33864. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33865. * 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
  33866. * and the distance of this point from the begining of the path :
  33867. * ```javascript
  33868. * var scaleFunction = function(i, distance) {
  33869. * // do things
  33870. * return scaleValue;}
  33871. * ```
  33872. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33873. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33874. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33875. * 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
  33876. * 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
  33877. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33878. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33879. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33881. */
  33882. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33883. var options = {
  33884. shape: shape,
  33885. path: path,
  33886. scaleFunction: scaleFunction,
  33887. rotationFunction: rotationFunction,
  33888. ribbonCloseArray: ribbonCloseArray,
  33889. ribbonClosePath: ribbonClosePath,
  33890. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33891. sideOrientation: sideOrientation,
  33892. instance: instance,
  33893. updatable: updatable
  33894. };
  33895. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33896. };
  33897. /**
  33898. * Creates lathe mesh.
  33899. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33900. * Please consider using the same method from the MeshBuilder class instead.
  33901. * 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
  33902. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33903. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33904. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33905. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33906. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33908. */
  33909. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33910. var options = {
  33911. shape: shape,
  33912. radius: radius,
  33913. tessellation: tessellation,
  33914. sideOrientation: sideOrientation,
  33915. updatable: updatable
  33916. };
  33917. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33918. };
  33919. /**
  33920. * Creates a plane mesh.
  33921. * Please consider using the same method from the MeshBuilder class instead.
  33922. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33923. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33924. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33926. */
  33927. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33928. var options = {
  33929. size: size,
  33930. width: size,
  33931. height: size,
  33932. sideOrientation: sideOrientation,
  33933. updatable: updatable
  33934. };
  33935. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33936. };
  33937. /**
  33938. * Creates a ground mesh.
  33939. * Please consider using the same method from the MeshBuilder class instead.
  33940. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33941. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33943. */
  33944. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33945. var options = {
  33946. width: width,
  33947. height: height,
  33948. subdivisions: subdivisions,
  33949. updatable: updatable
  33950. };
  33951. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33952. };
  33953. /**
  33954. * Creates a tiled ground mesh.
  33955. * Please consider using the same method from the MeshBuilder class instead.
  33956. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33957. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33958. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33959. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33960. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33961. * numbers of subdivisions on the ground width and height of each tile.
  33962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33963. */
  33964. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33965. var options = {
  33966. xmin: xmin,
  33967. zmin: zmin,
  33968. xmax: xmax,
  33969. zmax: zmax,
  33970. subdivisions: subdivisions,
  33971. precision: precision,
  33972. updatable: updatable
  33973. };
  33974. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33975. };
  33976. /**
  33977. * Creates a ground mesh from a height map.
  33978. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33979. * Please consider using the same method from the MeshBuilder class instead.
  33980. * The parameter `url` sets the URL of the height map image resource.
  33981. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33982. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33983. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33984. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33985. * 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).
  33986. * This function is passed the newly built mesh :
  33987. * ```javascript
  33988. * function(mesh) { // do things
  33989. * return; }
  33990. * ```
  33991. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33992. */
  33993. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33994. var options = {
  33995. width: width,
  33996. height: height,
  33997. subdivisions: subdivisions,
  33998. minHeight: minHeight,
  33999. maxHeight: maxHeight,
  34000. updatable: updatable,
  34001. onReady: onReady
  34002. };
  34003. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34004. };
  34005. /**
  34006. * Creates a tube mesh.
  34007. * 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.
  34008. * Please consider using the same method from the MeshBuilder class instead.
  34009. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34010. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34011. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34012. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34013. * 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.
  34014. * It must return a radius value (positive float) :
  34015. * ```javascript
  34016. * var radiusFunction = function(i, distance) {
  34017. * // do things
  34018. * return radius; }
  34019. * ```
  34020. * 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
  34021. * 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
  34022. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34023. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34025. */
  34026. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34027. var options = {
  34028. path: path,
  34029. radius: radius,
  34030. tessellation: tessellation,
  34031. radiusFunction: radiusFunction,
  34032. arc: 1,
  34033. cap: cap,
  34034. updatable: updatable,
  34035. sideOrientation: sideOrientation,
  34036. instance: instance
  34037. };
  34038. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34039. };
  34040. /**
  34041. * Creates a polyhedron mesh.
  34042. * Please consider using the same method from the MeshBuilder class instead.
  34043. * 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
  34044. * to choose the wanted type.
  34045. * The parameter `size` (positive float, default 1) sets the polygon size.
  34046. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34047. * 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`.
  34048. * 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
  34049. * 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)`).
  34050. * 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
  34051. * 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.
  34052. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34053. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34055. */
  34056. Mesh.CreatePolyhedron = function (name, options, scene) {
  34057. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34058. };
  34059. /**
  34060. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34061. * Please consider using the same method from the MeshBuilder class instead.
  34062. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34063. * 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`).
  34064. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34065. * 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.
  34066. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34067. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34068. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34069. */
  34070. Mesh.CreateIcoSphere = function (name, options, scene) {
  34071. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34072. };
  34073. /**
  34074. * Creates a decal mesh.
  34075. * Please consider using the same method from the MeshBuilder class instead.
  34076. * 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.
  34077. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34078. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34079. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34080. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34081. */
  34082. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34083. var options = {
  34084. position: position,
  34085. normal: normal,
  34086. size: size,
  34087. angle: angle
  34088. };
  34089. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34090. };
  34091. // Skeletons
  34092. /**
  34093. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34094. */
  34095. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34096. if (!this._sourcePositions) {
  34097. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34098. if (!source) {
  34099. return this._sourcePositions;
  34100. }
  34101. this._sourcePositions = new Float32Array(source);
  34102. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34103. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34104. }
  34105. }
  34106. return this._sourcePositions;
  34107. };
  34108. /**
  34109. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34110. */
  34111. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34112. if (!this._sourceNormals) {
  34113. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34114. if (!source) {
  34115. return this._sourceNormals;
  34116. }
  34117. this._sourceNormals = new Float32Array(source);
  34118. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34119. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34120. }
  34121. }
  34122. return this._sourceNormals;
  34123. };
  34124. /**
  34125. * Updates the vertex buffer by applying transformation from the bones.
  34126. * Returns the Mesh.
  34127. *
  34128. * @param {skeleton} skeleton to apply
  34129. */
  34130. Mesh.prototype.applySkeleton = function (skeleton) {
  34131. if (!this.geometry) {
  34132. return this;
  34133. }
  34134. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34135. return this;
  34136. }
  34137. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34138. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34139. return this;
  34140. }
  34141. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34142. return this;
  34143. }
  34144. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34145. return this;
  34146. }
  34147. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34148. return this;
  34149. }
  34150. if (!this._sourcePositions) {
  34151. var submeshes = this.subMeshes.slice();
  34152. this.setPositionsForCPUSkinning();
  34153. this.subMeshes = submeshes;
  34154. }
  34155. if (!this._sourceNormals) {
  34156. this.setNormalsForCPUSkinning();
  34157. }
  34158. // positionsData checks for not being Float32Array will only pass at most once
  34159. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34160. if (!positionsData) {
  34161. return this;
  34162. }
  34163. if (!(positionsData instanceof Float32Array)) {
  34164. positionsData = new Float32Array(positionsData);
  34165. }
  34166. // normalsData checks for not being Float32Array will only pass at most once
  34167. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34168. if (!normalsData) {
  34169. return this;
  34170. }
  34171. if (!(normalsData instanceof Float32Array)) {
  34172. normalsData = new Float32Array(normalsData);
  34173. }
  34174. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34175. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34176. if (!matricesWeightsData || !matricesIndicesData) {
  34177. return this;
  34178. }
  34179. var needExtras = this.numBoneInfluencers > 4;
  34180. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34181. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34182. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34183. var tempVector3 = BABYLON.Vector3.Zero();
  34184. var finalMatrix = new BABYLON.Matrix();
  34185. var tempMatrix = new BABYLON.Matrix();
  34186. var matWeightIdx = 0;
  34187. var inf;
  34188. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34189. var weight;
  34190. for (inf = 0; inf < 4; inf++) {
  34191. weight = matricesWeightsData[matWeightIdx + inf];
  34192. if (weight > 0) {
  34193. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34194. finalMatrix.addToSelf(tempMatrix);
  34195. }
  34196. else
  34197. break;
  34198. }
  34199. if (needExtras) {
  34200. for (inf = 0; inf < 4; inf++) {
  34201. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34202. if (weight > 0) {
  34203. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34204. finalMatrix.addToSelf(tempMatrix);
  34205. }
  34206. else
  34207. break;
  34208. }
  34209. }
  34210. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34211. tempVector3.toArray(positionsData, index);
  34212. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34213. tempVector3.toArray(normalsData, index);
  34214. finalMatrix.reset();
  34215. }
  34216. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34217. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34218. return this;
  34219. };
  34220. // Tools
  34221. /**
  34222. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34223. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34224. */
  34225. Mesh.MinMax = function (meshes) {
  34226. var minVector = null;
  34227. var maxVector = null;
  34228. meshes.forEach(function (mesh, index, array) {
  34229. var boundingInfo = mesh.getBoundingInfo();
  34230. var boundingBox = boundingInfo.boundingBox;
  34231. if (!minVector || !maxVector) {
  34232. minVector = boundingBox.minimumWorld;
  34233. maxVector = boundingBox.maximumWorld;
  34234. }
  34235. else {
  34236. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34237. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34238. }
  34239. });
  34240. if (!minVector || !maxVector) {
  34241. return {
  34242. min: BABYLON.Vector3.Zero(),
  34243. max: BABYLON.Vector3.Zero()
  34244. };
  34245. }
  34246. return {
  34247. min: minVector,
  34248. max: maxVector
  34249. };
  34250. };
  34251. /**
  34252. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34253. */
  34254. Mesh.Center = function (meshesOrMinMaxVector) {
  34255. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34256. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34257. };
  34258. /**
  34259. * Merge the array of meshes into a single mesh for performance reasons.
  34260. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34261. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34262. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34263. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34264. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34265. */
  34266. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34267. if (disposeSource === void 0) { disposeSource = true; }
  34268. var index;
  34269. if (!allow32BitsIndices) {
  34270. var totalVertices = 0;
  34271. // Counting vertices
  34272. for (index = 0; index < meshes.length; index++) {
  34273. if (meshes[index]) {
  34274. totalVertices += meshes[index].getTotalVertices();
  34275. if (totalVertices > 65536) {
  34276. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34277. return null;
  34278. }
  34279. }
  34280. }
  34281. }
  34282. // Merge
  34283. var vertexData = null;
  34284. var otherVertexData;
  34285. var indiceArray = new Array();
  34286. var source = null;
  34287. for (index = 0; index < meshes.length; index++) {
  34288. if (meshes[index]) {
  34289. meshes[index].computeWorldMatrix(true);
  34290. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34291. otherVertexData.transform(meshes[index].getWorldMatrix());
  34292. if (vertexData) {
  34293. vertexData.merge(otherVertexData);
  34294. }
  34295. else {
  34296. vertexData = otherVertexData;
  34297. source = meshes[index];
  34298. }
  34299. if (subdivideWithSubMeshes) {
  34300. indiceArray.push(meshes[index].getTotalIndices());
  34301. }
  34302. }
  34303. }
  34304. source = source;
  34305. if (!meshSubclass) {
  34306. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34307. }
  34308. vertexData.applyToMesh(meshSubclass);
  34309. // Setting properties
  34310. meshSubclass.material = source.material;
  34311. meshSubclass.checkCollisions = source.checkCollisions;
  34312. // Cleaning
  34313. if (disposeSource) {
  34314. for (index = 0; index < meshes.length; index++) {
  34315. if (meshes[index]) {
  34316. meshes[index].dispose();
  34317. }
  34318. }
  34319. }
  34320. // Subdivide
  34321. if (subdivideWithSubMeshes) {
  34322. //-- removal of global submesh
  34323. meshSubclass.releaseSubMeshes();
  34324. index = 0;
  34325. var offset = 0;
  34326. //-- apply subdivision according to index table
  34327. while (index < indiceArray.length) {
  34328. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34329. offset += indiceArray[index];
  34330. index++;
  34331. }
  34332. }
  34333. return meshSubclass;
  34334. };
  34335. // Consts
  34336. Mesh._FRONTSIDE = 0;
  34337. Mesh._BACKSIDE = 1;
  34338. Mesh._DOUBLESIDE = 2;
  34339. Mesh._DEFAULTSIDE = 0;
  34340. Mesh._NO_CAP = 0;
  34341. Mesh._CAP_START = 1;
  34342. Mesh._CAP_END = 2;
  34343. Mesh._CAP_ALL = 3;
  34344. return Mesh;
  34345. }(BABYLON.AbstractMesh));
  34346. BABYLON.Mesh = Mesh;
  34347. })(BABYLON || (BABYLON = {}));
  34348. //# sourceMappingURL=babylon.mesh.js.map
  34349. var BABYLON;
  34350. (function (BABYLON) {
  34351. var BaseSubMesh = /** @class */ (function () {
  34352. function BaseSubMesh() {
  34353. }
  34354. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34355. get: function () {
  34356. return this._materialEffect;
  34357. },
  34358. enumerable: true,
  34359. configurable: true
  34360. });
  34361. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34362. if (defines === void 0) { defines = null; }
  34363. if (this._materialEffect === effect) {
  34364. if (!effect) {
  34365. this._materialDefines = null;
  34366. }
  34367. return;
  34368. }
  34369. this._materialDefines = defines;
  34370. this._materialEffect = effect;
  34371. };
  34372. return BaseSubMesh;
  34373. }());
  34374. BABYLON.BaseSubMesh = BaseSubMesh;
  34375. var SubMesh = /** @class */ (function (_super) {
  34376. __extends(SubMesh, _super);
  34377. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34378. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34379. var _this = _super.call(this) || this;
  34380. _this.materialIndex = materialIndex;
  34381. _this.verticesStart = verticesStart;
  34382. _this.verticesCount = verticesCount;
  34383. _this.indexStart = indexStart;
  34384. _this.indexCount = indexCount;
  34385. _this._renderId = 0;
  34386. _this._mesh = mesh;
  34387. _this._renderingMesh = renderingMesh || mesh;
  34388. mesh.subMeshes.push(_this);
  34389. _this._trianglePlanes = [];
  34390. _this._id = mesh.subMeshes.length - 1;
  34391. if (createBoundingBox) {
  34392. _this.refreshBoundingInfo();
  34393. mesh.computeWorldMatrix(true);
  34394. }
  34395. return _this;
  34396. }
  34397. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34398. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34399. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34400. };
  34401. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34402. get: function () {
  34403. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34404. },
  34405. enumerable: true,
  34406. configurable: true
  34407. });
  34408. /**
  34409. * Returns the submesh BoudingInfo object.
  34410. */
  34411. SubMesh.prototype.getBoundingInfo = function () {
  34412. if (this.IsGlobal) {
  34413. return this._mesh.getBoundingInfo();
  34414. }
  34415. return this._boundingInfo;
  34416. };
  34417. /**
  34418. * Sets the submesh BoundingInfo.
  34419. * Return the SubMesh.
  34420. */
  34421. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34422. this._boundingInfo = boundingInfo;
  34423. return this;
  34424. };
  34425. /**
  34426. * Returns the mesh of the current submesh.
  34427. */
  34428. SubMesh.prototype.getMesh = function () {
  34429. return this._mesh;
  34430. };
  34431. /**
  34432. * Returns the rendering mesh of the submesh.
  34433. */
  34434. SubMesh.prototype.getRenderingMesh = function () {
  34435. return this._renderingMesh;
  34436. };
  34437. /**
  34438. * Returns the submesh material.
  34439. */
  34440. SubMesh.prototype.getMaterial = function () {
  34441. var rootMaterial = this._renderingMesh.material;
  34442. if (rootMaterial === null || rootMaterial === undefined) {
  34443. return this._mesh.getScene().defaultMaterial;
  34444. }
  34445. else if (rootMaterial.getSubMaterial) {
  34446. var multiMaterial = rootMaterial;
  34447. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34448. if (this._currentMaterial !== effectiveMaterial) {
  34449. this._currentMaterial = effectiveMaterial;
  34450. this._materialDefines = null;
  34451. }
  34452. return effectiveMaterial;
  34453. }
  34454. return rootMaterial;
  34455. };
  34456. // Methods
  34457. /**
  34458. * Sets a new updated BoundingInfo object to the submesh.
  34459. * Returns the SubMesh.
  34460. */
  34461. SubMesh.prototype.refreshBoundingInfo = function () {
  34462. this._lastColliderWorldVertices = null;
  34463. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34464. return this;
  34465. }
  34466. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34467. if (!data) {
  34468. this._boundingInfo = this._mesh.getBoundingInfo();
  34469. return this;
  34470. }
  34471. var indices = this._renderingMesh.getIndices();
  34472. var extend;
  34473. //is this the only submesh?
  34474. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34475. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34476. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34477. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34478. }
  34479. else {
  34480. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34481. }
  34482. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34483. return this;
  34484. };
  34485. SubMesh.prototype._checkCollision = function (collider) {
  34486. var boundingInfo = this.getBoundingInfo();
  34487. return boundingInfo._checkCollision(collider);
  34488. };
  34489. /**
  34490. * Updates the submesh BoundingInfo.
  34491. * Returns the Submesh.
  34492. */
  34493. SubMesh.prototype.updateBoundingInfo = function (world) {
  34494. var boundingInfo = this.getBoundingInfo();
  34495. if (!boundingInfo) {
  34496. this.refreshBoundingInfo();
  34497. boundingInfo = this.getBoundingInfo();
  34498. }
  34499. boundingInfo.update(world);
  34500. return this;
  34501. };
  34502. /**
  34503. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34504. * Boolean returned.
  34505. */
  34506. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34507. var boundingInfo = this.getBoundingInfo();
  34508. if (!boundingInfo) {
  34509. return false;
  34510. }
  34511. return boundingInfo.isInFrustum(frustumPlanes);
  34512. };
  34513. /**
  34514. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34515. * Boolean returned.
  34516. */
  34517. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34518. var boundingInfo = this.getBoundingInfo();
  34519. if (!boundingInfo) {
  34520. return false;
  34521. }
  34522. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34523. };
  34524. /**
  34525. * Renders the submesh.
  34526. * Returns it.
  34527. */
  34528. SubMesh.prototype.render = function (enableAlphaMode) {
  34529. this._renderingMesh.render(this, enableAlphaMode);
  34530. return this;
  34531. };
  34532. /**
  34533. * Returns a new Index Buffer.
  34534. * Type returned : WebGLBuffer.
  34535. */
  34536. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34537. if (!this._linesIndexBuffer) {
  34538. var linesIndices = [];
  34539. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34540. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34541. }
  34542. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34543. this.linesIndexCount = linesIndices.length;
  34544. }
  34545. return this._linesIndexBuffer;
  34546. };
  34547. /**
  34548. * True is the passed Ray intersects the submesh bounding box.
  34549. * Boolean returned.
  34550. */
  34551. SubMesh.prototype.canIntersects = function (ray) {
  34552. var boundingInfo = this.getBoundingInfo();
  34553. if (!boundingInfo) {
  34554. return false;
  34555. }
  34556. return ray.intersectsBox(boundingInfo.boundingBox);
  34557. };
  34558. /**
  34559. * Returns an object IntersectionInfo.
  34560. */
  34561. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34562. var intersectInfo = null;
  34563. var material = this.getMaterial();
  34564. if (!material) {
  34565. return null;
  34566. }
  34567. switch (material.fillMode) {
  34568. case BABYLON.Material.PointListDrawMode:
  34569. case BABYLON.Material.LineListDrawMode:
  34570. case BABYLON.Material.LineLoopDrawMode:
  34571. case BABYLON.Material.LineStripDrawMode:
  34572. case BABYLON.Material.TriangleFanDrawMode:
  34573. case BABYLON.Material.TriangleStripDrawMode:
  34574. return null;
  34575. }
  34576. // LineMesh first as it's also a Mesh...
  34577. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34578. var lineMesh = this._mesh;
  34579. // Line test
  34580. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34581. var p0 = positions[indices[index]];
  34582. var p1 = positions[indices[index + 1]];
  34583. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34584. if (length < 0) {
  34585. continue;
  34586. }
  34587. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34588. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34589. if (fastCheck) {
  34590. break;
  34591. }
  34592. }
  34593. }
  34594. }
  34595. else {
  34596. // Triangles test
  34597. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34598. var p0 = positions[indices[index]];
  34599. var p1 = positions[indices[index + 1]];
  34600. var p2 = positions[indices[index + 2]];
  34601. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34602. if (currentIntersectInfo) {
  34603. if (currentIntersectInfo.distance < 0) {
  34604. continue;
  34605. }
  34606. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34607. intersectInfo = currentIntersectInfo;
  34608. intersectInfo.faceId = index / 3;
  34609. if (fastCheck) {
  34610. break;
  34611. }
  34612. }
  34613. }
  34614. }
  34615. }
  34616. return intersectInfo;
  34617. };
  34618. SubMesh.prototype._rebuild = function () {
  34619. if (this._linesIndexBuffer) {
  34620. this._linesIndexBuffer = null;
  34621. }
  34622. };
  34623. // Clone
  34624. /**
  34625. * Creates a new Submesh from the passed Mesh.
  34626. */
  34627. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34628. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34629. if (!this.IsGlobal) {
  34630. var boundingInfo = this.getBoundingInfo();
  34631. if (!boundingInfo) {
  34632. return result;
  34633. }
  34634. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34635. }
  34636. return result;
  34637. };
  34638. // Dispose
  34639. /**
  34640. * Disposes the Submesh.
  34641. * Returns nothing.
  34642. */
  34643. SubMesh.prototype.dispose = function () {
  34644. if (this._linesIndexBuffer) {
  34645. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34646. this._linesIndexBuffer = null;
  34647. }
  34648. // Remove from mesh
  34649. var index = this._mesh.subMeshes.indexOf(this);
  34650. this._mesh.subMeshes.splice(index, 1);
  34651. };
  34652. // Statics
  34653. /**
  34654. * Creates a new Submesh from the passed parameters :
  34655. * - materialIndex (integer) : the index of the main mesh material.
  34656. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34657. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34658. * - mesh (Mesh) : the main mesh to create the submesh from.
  34659. * - renderingMesh (optional Mesh) : rendering mesh.
  34660. */
  34661. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34662. var minVertexIndex = Number.MAX_VALUE;
  34663. var maxVertexIndex = -Number.MAX_VALUE;
  34664. renderingMesh = (renderingMesh || mesh);
  34665. var indices = renderingMesh.getIndices();
  34666. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34667. var vertexIndex = indices[index];
  34668. if (vertexIndex < minVertexIndex)
  34669. minVertexIndex = vertexIndex;
  34670. if (vertexIndex > maxVertexIndex)
  34671. maxVertexIndex = vertexIndex;
  34672. }
  34673. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34674. };
  34675. return SubMesh;
  34676. }(BaseSubMesh));
  34677. BABYLON.SubMesh = SubMesh;
  34678. })(BABYLON || (BABYLON = {}));
  34679. //# sourceMappingURL=babylon.subMesh.js.map
  34680. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34681. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34682. s = arguments[i];
  34683. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34684. t[p] = s[p];
  34685. }
  34686. return t;
  34687. };
  34688. var BABYLON;
  34689. (function (BABYLON) {
  34690. /**
  34691. * Manages the defines for the Material
  34692. */
  34693. var MaterialDefines = /** @class */ (function () {
  34694. function MaterialDefines() {
  34695. this._isDirty = true;
  34696. /** @hidden */
  34697. this._areLightsDirty = true;
  34698. /** @hidden */
  34699. this._areAttributesDirty = true;
  34700. /** @hidden */
  34701. this._areTexturesDirty = true;
  34702. /** @hidden */
  34703. this._areFresnelDirty = true;
  34704. /** @hidden */
  34705. this._areMiscDirty = true;
  34706. /** @hidden */
  34707. this._areImageProcessingDirty = true;
  34708. /** @hidden */
  34709. this._normals = false;
  34710. /** @hidden */
  34711. this._uvs = false;
  34712. /** @hidden */
  34713. this._needNormals = false;
  34714. /** @hidden */
  34715. this._needUVs = false;
  34716. }
  34717. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34718. /**
  34719. * Specifies if the material needs to be re-calculated
  34720. */
  34721. get: function () {
  34722. return this._isDirty;
  34723. },
  34724. enumerable: true,
  34725. configurable: true
  34726. });
  34727. /**
  34728. * Marks the material to indicate that it has been re-calculated
  34729. */
  34730. MaterialDefines.prototype.markAsProcessed = function () {
  34731. this._isDirty = false;
  34732. this._areAttributesDirty = false;
  34733. this._areTexturesDirty = false;
  34734. this._areFresnelDirty = false;
  34735. this._areLightsDirty = false;
  34736. this._areMiscDirty = false;
  34737. this._areImageProcessingDirty = false;
  34738. };
  34739. /**
  34740. * Marks the material to indicate that it needs to be re-calculated
  34741. */
  34742. MaterialDefines.prototype.markAsUnprocessed = function () {
  34743. this._isDirty = true;
  34744. };
  34745. /**
  34746. * Marks the material to indicate all of its defines need to be re-calculated
  34747. */
  34748. MaterialDefines.prototype.markAllAsDirty = function () {
  34749. this._areTexturesDirty = true;
  34750. this._areAttributesDirty = true;
  34751. this._areLightsDirty = true;
  34752. this._areFresnelDirty = true;
  34753. this._areMiscDirty = true;
  34754. this._areImageProcessingDirty = true;
  34755. this._isDirty = true;
  34756. };
  34757. /**
  34758. * Marks the material to indicate that image processing needs to be re-calculated
  34759. */
  34760. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34761. this._areImageProcessingDirty = true;
  34762. this._isDirty = true;
  34763. };
  34764. /**
  34765. * Marks the material to indicate the lights need to be re-calculated
  34766. */
  34767. MaterialDefines.prototype.markAsLightDirty = function () {
  34768. this._areLightsDirty = true;
  34769. this._isDirty = true;
  34770. };
  34771. /**
  34772. * Marks the attribute state as changed
  34773. */
  34774. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34775. this._areAttributesDirty = true;
  34776. this._isDirty = true;
  34777. };
  34778. /**
  34779. * Marks the texture state as changed
  34780. */
  34781. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34782. this._areTexturesDirty = true;
  34783. this._isDirty = true;
  34784. };
  34785. /**
  34786. * Marks the fresnel state as changed
  34787. */
  34788. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34789. this._areFresnelDirty = true;
  34790. this._isDirty = true;
  34791. };
  34792. /**
  34793. * Marks the misc state as changed
  34794. */
  34795. MaterialDefines.prototype.markAsMiscDirty = function () {
  34796. this._areMiscDirty = true;
  34797. this._isDirty = true;
  34798. };
  34799. /**
  34800. * Rebuilds the material defines
  34801. */
  34802. MaterialDefines.prototype.rebuild = function () {
  34803. if (this._keys) {
  34804. delete this._keys;
  34805. }
  34806. this._keys = [];
  34807. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34808. var key = _a[_i];
  34809. if (key[0] === "_") {
  34810. continue;
  34811. }
  34812. this._keys.push(key);
  34813. }
  34814. };
  34815. /**
  34816. * Specifies if two material defines are equal
  34817. * @param other - A material define instance to compare to
  34818. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34819. */
  34820. MaterialDefines.prototype.isEqual = function (other) {
  34821. if (this._keys.length !== other._keys.length) {
  34822. return false;
  34823. }
  34824. for (var index = 0; index < this._keys.length; index++) {
  34825. var prop = this._keys[index];
  34826. if (this[prop] !== other[prop]) {
  34827. return false;
  34828. }
  34829. }
  34830. return true;
  34831. };
  34832. /**
  34833. * Clones this instance's defines to another instance
  34834. * @param other - material defines to clone values to
  34835. */
  34836. MaterialDefines.prototype.cloneTo = function (other) {
  34837. if (this._keys.length !== other._keys.length) {
  34838. other._keys = this._keys.slice(0);
  34839. }
  34840. for (var index = 0; index < this._keys.length; index++) {
  34841. var prop = this._keys[index];
  34842. other[prop] = this[prop];
  34843. }
  34844. };
  34845. /**
  34846. * Resets the material define values
  34847. */
  34848. MaterialDefines.prototype.reset = function () {
  34849. for (var index = 0; index < this._keys.length; index++) {
  34850. var prop = this._keys[index];
  34851. var type = typeof this[prop];
  34852. switch (type) {
  34853. case "number":
  34854. this[prop] = 0;
  34855. break;
  34856. case "string":
  34857. this[prop] = "";
  34858. break;
  34859. default:
  34860. this[prop] = false;
  34861. break;
  34862. }
  34863. }
  34864. };
  34865. /**
  34866. * Converts the material define values to a string
  34867. * @returns - String of material define information
  34868. */
  34869. MaterialDefines.prototype.toString = function () {
  34870. var result = "";
  34871. for (var index = 0; index < this._keys.length; index++) {
  34872. var prop = this._keys[index];
  34873. var value = this[prop];
  34874. var type = typeof value;
  34875. switch (type) {
  34876. case "number":
  34877. case "string":
  34878. result += "#define " + prop + " " + value + "\n";
  34879. break;
  34880. default:
  34881. if (value) {
  34882. result += "#define " + prop + "\n";
  34883. }
  34884. break;
  34885. }
  34886. }
  34887. return result;
  34888. };
  34889. return MaterialDefines;
  34890. }());
  34891. BABYLON.MaterialDefines = MaterialDefines;
  34892. /**
  34893. * Base class for the main features of a material in Babylon.js
  34894. */
  34895. var Material = /** @class */ (function () {
  34896. /**
  34897. * Creates a material instance
  34898. * @param name defines the name of the material
  34899. * @param scene defines the scene to reference
  34900. * @param doNotAdd specifies if the material should be added to the scene
  34901. */
  34902. function Material(name, scene, doNotAdd) {
  34903. /**
  34904. * Specifies if the ready state should be checked on each call
  34905. */
  34906. this.checkReadyOnEveryCall = false;
  34907. /**
  34908. * Specifies if the ready state should be checked once
  34909. */
  34910. this.checkReadyOnlyOnce = false;
  34911. /**
  34912. * The state of the material
  34913. */
  34914. this.state = "";
  34915. /**
  34916. * The alpha value of the material
  34917. */
  34918. this._alpha = 1.0;
  34919. /**
  34920. * Specifies if back face culling is enabled
  34921. */
  34922. this._backFaceCulling = true;
  34923. /**
  34924. * Specifies if the material should be serialized
  34925. */
  34926. this.doNotSerialize = false;
  34927. /**
  34928. * Specifies if the effect should be stored on sub meshes
  34929. */
  34930. this.storeEffectOnSubMeshes = false;
  34931. /**
  34932. * An event triggered when the material is disposed
  34933. */
  34934. this.onDisposeObservable = new BABYLON.Observable();
  34935. /**
  34936. * An event triggered when the material is bound
  34937. */
  34938. this.onBindObservable = new BABYLON.Observable();
  34939. /**
  34940. * An event triggered when the material is unbound
  34941. */
  34942. this.onUnBindObservable = new BABYLON.Observable();
  34943. /**
  34944. * Stores the value of the alpha mode
  34945. */
  34946. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34947. /**
  34948. * Stores the state of the need depth pre-pass value
  34949. */
  34950. this._needDepthPrePass = false;
  34951. /**
  34952. * Specifies if depth writing should be disabled
  34953. */
  34954. this.disableDepthWrite = false;
  34955. /**
  34956. * Specifies if depth writing should be forced
  34957. */
  34958. this.forceDepthWrite = false;
  34959. /**
  34960. * Specifies if there should be a separate pass for culling
  34961. */
  34962. this.separateCullingPass = false;
  34963. /**
  34964. * Stores the state specifing if fog should be enabled
  34965. */
  34966. this._fogEnabled = true;
  34967. /**
  34968. * Stores the size of points
  34969. */
  34970. this.pointSize = 1.0;
  34971. /**
  34972. * Stores the z offset value
  34973. */
  34974. this.zOffset = 0;
  34975. /**
  34976. * Specifies if the material was previously ready
  34977. */
  34978. this._wasPreviouslyReady = false;
  34979. /**
  34980. * Stores the fill mode state
  34981. */
  34982. this._fillMode = Material.TriangleFillMode;
  34983. this.name = name;
  34984. this.id = name || BABYLON.Tools.RandomId();
  34985. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34986. this.uniqueId = this._scene.getUniqueId();
  34987. if (this._scene.useRightHandedSystem) {
  34988. this.sideOrientation = Material.ClockWiseSideOrientation;
  34989. }
  34990. else {
  34991. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34992. }
  34993. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34994. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34995. if (!doNotAdd) {
  34996. this._scene.materials.push(this);
  34997. }
  34998. }
  34999. Object.defineProperty(Material, "TriangleFillMode", {
  35000. /**
  35001. * Returns the triangle fill mode
  35002. */
  35003. get: function () {
  35004. return Material._TriangleFillMode;
  35005. },
  35006. enumerable: true,
  35007. configurable: true
  35008. });
  35009. Object.defineProperty(Material, "WireFrameFillMode", {
  35010. /**
  35011. * Returns the wireframe mode
  35012. */
  35013. get: function () {
  35014. return Material._WireFrameFillMode;
  35015. },
  35016. enumerable: true,
  35017. configurable: true
  35018. });
  35019. Object.defineProperty(Material, "PointFillMode", {
  35020. /**
  35021. * Returns the point fill mode
  35022. */
  35023. get: function () {
  35024. return Material._PointFillMode;
  35025. },
  35026. enumerable: true,
  35027. configurable: true
  35028. });
  35029. Object.defineProperty(Material, "PointListDrawMode", {
  35030. /**
  35031. * Returns the point list draw mode
  35032. */
  35033. get: function () {
  35034. return Material._PointListDrawMode;
  35035. },
  35036. enumerable: true,
  35037. configurable: true
  35038. });
  35039. Object.defineProperty(Material, "LineListDrawMode", {
  35040. /**
  35041. * Returns the line list draw mode
  35042. */
  35043. get: function () {
  35044. return Material._LineListDrawMode;
  35045. },
  35046. enumerable: true,
  35047. configurable: true
  35048. });
  35049. Object.defineProperty(Material, "LineLoopDrawMode", {
  35050. /**
  35051. * Returns the line loop draw mode
  35052. */
  35053. get: function () {
  35054. return Material._LineLoopDrawMode;
  35055. },
  35056. enumerable: true,
  35057. configurable: true
  35058. });
  35059. Object.defineProperty(Material, "LineStripDrawMode", {
  35060. /**
  35061. * Returns the line strip draw mode
  35062. */
  35063. get: function () {
  35064. return Material._LineStripDrawMode;
  35065. },
  35066. enumerable: true,
  35067. configurable: true
  35068. });
  35069. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35070. /**
  35071. * Returns the triangle strip draw mode
  35072. */
  35073. get: function () {
  35074. return Material._TriangleStripDrawMode;
  35075. },
  35076. enumerable: true,
  35077. configurable: true
  35078. });
  35079. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35080. /**
  35081. * Returns the triangle fan draw mode
  35082. */
  35083. get: function () {
  35084. return Material._TriangleFanDrawMode;
  35085. },
  35086. enumerable: true,
  35087. configurable: true
  35088. });
  35089. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35090. /**
  35091. * Returns the clock-wise side orientation
  35092. */
  35093. get: function () {
  35094. return Material._ClockWiseSideOrientation;
  35095. },
  35096. enumerable: true,
  35097. configurable: true
  35098. });
  35099. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35100. /**
  35101. * Returns the counter clock-wise side orientation
  35102. */
  35103. get: function () {
  35104. return Material._CounterClockWiseSideOrientation;
  35105. },
  35106. enumerable: true,
  35107. configurable: true
  35108. });
  35109. Object.defineProperty(Material, "TextureDirtyFlag", {
  35110. /**
  35111. * Returns the dirty texture flag value
  35112. */
  35113. get: function () {
  35114. return Material._TextureDirtyFlag;
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. Object.defineProperty(Material, "LightDirtyFlag", {
  35120. /**
  35121. * Returns the dirty light flag value
  35122. */
  35123. get: function () {
  35124. return Material._LightDirtyFlag;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35130. /**
  35131. * Returns the dirty fresnel flag value
  35132. */
  35133. get: function () {
  35134. return Material._FresnelDirtyFlag;
  35135. },
  35136. enumerable: true,
  35137. configurable: true
  35138. });
  35139. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35140. /**
  35141. * Returns the dirty attributes flag value
  35142. */
  35143. get: function () {
  35144. return Material._AttributesDirtyFlag;
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. Object.defineProperty(Material, "MiscDirtyFlag", {
  35150. /**
  35151. * Returns the dirty misc flag value
  35152. */
  35153. get: function () {
  35154. return Material._MiscDirtyFlag;
  35155. },
  35156. enumerable: true,
  35157. configurable: true
  35158. });
  35159. Object.defineProperty(Material.prototype, "alpha", {
  35160. /**
  35161. * Gets the alpha value of the material
  35162. */
  35163. get: function () {
  35164. return this._alpha;
  35165. },
  35166. /**
  35167. * Sets the alpha value of the material
  35168. */
  35169. set: function (value) {
  35170. if (this._alpha === value) {
  35171. return;
  35172. }
  35173. this._alpha = value;
  35174. this.markAsDirty(Material.MiscDirtyFlag);
  35175. },
  35176. enumerable: true,
  35177. configurable: true
  35178. });
  35179. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35180. /**
  35181. * Gets the back-face culling state
  35182. */
  35183. get: function () {
  35184. return this._backFaceCulling;
  35185. },
  35186. /**
  35187. * Sets the back-face culling state
  35188. */
  35189. set: function (value) {
  35190. if (this._backFaceCulling === value) {
  35191. return;
  35192. }
  35193. this._backFaceCulling = value;
  35194. this.markAsDirty(Material.TextureDirtyFlag);
  35195. },
  35196. enumerable: true,
  35197. configurable: true
  35198. });
  35199. Object.defineProperty(Material.prototype, "onDispose", {
  35200. /**
  35201. * Called during a dispose event
  35202. */
  35203. set: function (callback) {
  35204. if (this._onDisposeObserver) {
  35205. this.onDisposeObservable.remove(this._onDisposeObserver);
  35206. }
  35207. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35208. },
  35209. enumerable: true,
  35210. configurable: true
  35211. });
  35212. Object.defineProperty(Material.prototype, "onBind", {
  35213. /**
  35214. * Called during a bind event
  35215. */
  35216. set: function (callback) {
  35217. if (this._onBindObserver) {
  35218. this.onBindObservable.remove(this._onBindObserver);
  35219. }
  35220. this._onBindObserver = this.onBindObservable.add(callback);
  35221. },
  35222. enumerable: true,
  35223. configurable: true
  35224. });
  35225. Object.defineProperty(Material.prototype, "alphaMode", {
  35226. /**
  35227. * Gets the value of the alpha mode
  35228. */
  35229. get: function () {
  35230. return this._alphaMode;
  35231. },
  35232. /**
  35233. * Sets the value of the alpha mode.
  35234. *
  35235. * | Value | Type | Description |
  35236. * | --- | --- | --- |
  35237. * | 0 | ALPHA_DISABLE | |
  35238. * | 1 | ALPHA_ADD | |
  35239. * | 2 | ALPHA_COMBINE | |
  35240. * | 3 | ALPHA_SUBTRACT | |
  35241. * | 4 | ALPHA_MULTIPLY | |
  35242. * | 5 | ALPHA_MAXIMIZED | |
  35243. * | 6 | ALPHA_ONEONE | |
  35244. * | 7 | ALPHA_PREMULTIPLIED | |
  35245. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35246. * | 9 | ALPHA_INTERPOLATE | |
  35247. * | 10 | ALPHA_SCREENMODE | |
  35248. *
  35249. */
  35250. set: function (value) {
  35251. if (this._alphaMode === value) {
  35252. return;
  35253. }
  35254. this._alphaMode = value;
  35255. this.markAsDirty(Material.TextureDirtyFlag);
  35256. },
  35257. enumerable: true,
  35258. configurable: true
  35259. });
  35260. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35261. /**
  35262. * Gets the depth pre-pass value
  35263. */
  35264. get: function () {
  35265. return this._needDepthPrePass;
  35266. },
  35267. /**
  35268. * Sets the need depth pre-pass value
  35269. */
  35270. set: function (value) {
  35271. if (this._needDepthPrePass === value) {
  35272. return;
  35273. }
  35274. this._needDepthPrePass = value;
  35275. if (this._needDepthPrePass) {
  35276. this.checkReadyOnEveryCall = true;
  35277. }
  35278. },
  35279. enumerable: true,
  35280. configurable: true
  35281. });
  35282. Object.defineProperty(Material.prototype, "fogEnabled", {
  35283. /**
  35284. * Gets the value of the fog enabled state
  35285. */
  35286. get: function () {
  35287. return this._fogEnabled;
  35288. },
  35289. /**
  35290. * Sets the state for enabling fog
  35291. */
  35292. set: function (value) {
  35293. if (this._fogEnabled === value) {
  35294. return;
  35295. }
  35296. this._fogEnabled = value;
  35297. this.markAsDirty(Material.MiscDirtyFlag);
  35298. },
  35299. enumerable: true,
  35300. configurable: true
  35301. });
  35302. Object.defineProperty(Material.prototype, "wireframe", {
  35303. /**
  35304. * Gets a value specifying if wireframe mode is enabled
  35305. */
  35306. get: function () {
  35307. switch (this._fillMode) {
  35308. case Material.WireFrameFillMode:
  35309. case Material.LineListDrawMode:
  35310. case Material.LineLoopDrawMode:
  35311. case Material.LineStripDrawMode:
  35312. return true;
  35313. }
  35314. return this._scene.forceWireframe;
  35315. },
  35316. /**
  35317. * Sets the state of wireframe mode
  35318. */
  35319. set: function (value) {
  35320. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35321. },
  35322. enumerable: true,
  35323. configurable: true
  35324. });
  35325. Object.defineProperty(Material.prototype, "pointsCloud", {
  35326. /**
  35327. * Gets the value specifying if point clouds are enabled
  35328. */
  35329. get: function () {
  35330. switch (this._fillMode) {
  35331. case Material.PointFillMode:
  35332. case Material.PointListDrawMode:
  35333. return true;
  35334. }
  35335. return this._scene.forcePointsCloud;
  35336. },
  35337. /**
  35338. * Sets the state of point cloud mode
  35339. */
  35340. set: function (value) {
  35341. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35342. },
  35343. enumerable: true,
  35344. configurable: true
  35345. });
  35346. Object.defineProperty(Material.prototype, "fillMode", {
  35347. /**
  35348. * Gets the material fill mode
  35349. */
  35350. get: function () {
  35351. return this._fillMode;
  35352. },
  35353. /**
  35354. * Sets the material fill mode
  35355. */
  35356. set: function (value) {
  35357. if (this._fillMode === value) {
  35358. return;
  35359. }
  35360. this._fillMode = value;
  35361. this.markAsDirty(Material.MiscDirtyFlag);
  35362. },
  35363. enumerable: true,
  35364. configurable: true
  35365. });
  35366. /**
  35367. * Returns a string representation of the current material
  35368. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35369. * @returns a string with material information
  35370. */
  35371. Material.prototype.toString = function (fullDetails) {
  35372. var ret = "Name: " + this.name;
  35373. if (fullDetails) {
  35374. }
  35375. return ret;
  35376. };
  35377. /**
  35378. * Gets the class name of the material
  35379. * @returns a string with the class name of the material
  35380. */
  35381. Material.prototype.getClassName = function () {
  35382. return "Material";
  35383. };
  35384. Object.defineProperty(Material.prototype, "isFrozen", {
  35385. /**
  35386. * Specifies if updates for the material been locked
  35387. */
  35388. get: function () {
  35389. return this.checkReadyOnlyOnce;
  35390. },
  35391. enumerable: true,
  35392. configurable: true
  35393. });
  35394. /**
  35395. * Locks updates for the material
  35396. */
  35397. Material.prototype.freeze = function () {
  35398. this.checkReadyOnlyOnce = true;
  35399. };
  35400. /**
  35401. * Unlocks updates for the material
  35402. */
  35403. Material.prototype.unfreeze = function () {
  35404. this.checkReadyOnlyOnce = false;
  35405. };
  35406. /**
  35407. * Specifies if the material is ready to be used
  35408. * @param mesh defines the mesh to check
  35409. * @param useInstances specifies if instances should be used
  35410. * @returns a boolean indicating if the material is ready to be used
  35411. */
  35412. Material.prototype.isReady = function (mesh, useInstances) {
  35413. return true;
  35414. };
  35415. /**
  35416. * Specifies that the submesh is ready to be used
  35417. * @param mesh defines the mesh to check
  35418. * @param subMesh defines which submesh to check
  35419. * @param useInstances specifies that instances should be used
  35420. * @returns a boolean indicating that the submesh is ready or not
  35421. */
  35422. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35423. return false;
  35424. };
  35425. /**
  35426. * Returns the material effect
  35427. * @returns the effect associated with the material
  35428. */
  35429. Material.prototype.getEffect = function () {
  35430. return this._effect;
  35431. };
  35432. /**
  35433. * Returns the current scene
  35434. * @returns a Scene
  35435. */
  35436. Material.prototype.getScene = function () {
  35437. return this._scene;
  35438. };
  35439. /**
  35440. * Specifies if the material will require alpha blending
  35441. * @returns a boolean specifying if alpha blending is needed
  35442. */
  35443. Material.prototype.needAlphaBlending = function () {
  35444. return (this.alpha < 1.0);
  35445. };
  35446. /**
  35447. * Specifies if the mesh will require alpha blending
  35448. * @param mesh defines the mesh to check
  35449. * @returns a boolean specifying if alpha blending is needed for the mesh
  35450. */
  35451. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35452. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35453. };
  35454. /**
  35455. * Specifies if this material should be rendered in alpha test mode
  35456. * @returns a boolean specifying if an alpha test is needed.
  35457. */
  35458. Material.prototype.needAlphaTesting = function () {
  35459. return false;
  35460. };
  35461. /**
  35462. * Gets the texture used for the alpha test
  35463. * @returns the texture to use for alpha testing
  35464. */
  35465. Material.prototype.getAlphaTestTexture = function () {
  35466. return null;
  35467. };
  35468. /**
  35469. * Marks the material to indicate that it needs to be re-calculated
  35470. */
  35471. Material.prototype.markDirty = function () {
  35472. this._wasPreviouslyReady = false;
  35473. };
  35474. /** @hidden */
  35475. Material.prototype._preBind = function (effect, overrideOrientation) {
  35476. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35477. var engine = this._scene.getEngine();
  35478. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35479. var reverse = orientation === Material.ClockWiseSideOrientation;
  35480. engine.enableEffect(effect ? effect : this._effect);
  35481. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35482. return reverse;
  35483. };
  35484. /**
  35485. * Binds the material to the mesh
  35486. * @param world defines the world transformation matrix
  35487. * @param mesh defines the mesh to bind the material to
  35488. */
  35489. Material.prototype.bind = function (world, mesh) {
  35490. };
  35491. /**
  35492. * Binds the submesh to the material
  35493. * @param world defines the world transformation matrix
  35494. * @param mesh defines the mesh containing the submesh
  35495. * @param subMesh defines the submesh to bind the material to
  35496. */
  35497. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35498. };
  35499. /**
  35500. * Binds the world matrix to the material
  35501. * @param world defines the world transformation matrix
  35502. */
  35503. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35504. };
  35505. /**
  35506. * Binds the scene's uniform buffer to the effect.
  35507. * @param effect defines the effect to bind to the scene uniform buffer
  35508. * @param sceneUbo defines the uniform buffer storing scene data
  35509. */
  35510. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35511. sceneUbo.bindToEffect(effect, "Scene");
  35512. };
  35513. /**
  35514. * Binds the view matrix to the effect
  35515. * @param effect defines the effect to bind the view matrix to
  35516. */
  35517. Material.prototype.bindView = function (effect) {
  35518. if (!this._useUBO) {
  35519. effect.setMatrix("view", this.getScene().getViewMatrix());
  35520. }
  35521. else {
  35522. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35523. }
  35524. };
  35525. /**
  35526. * Binds the view projection matrix to the effect
  35527. * @param effect defines the effect to bind the view projection matrix to
  35528. */
  35529. Material.prototype.bindViewProjection = function (effect) {
  35530. if (!this._useUBO) {
  35531. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35532. }
  35533. else {
  35534. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35535. }
  35536. };
  35537. /**
  35538. * Specifies if material alpha testing should be turned on for the mesh
  35539. * @param mesh defines the mesh to check
  35540. */
  35541. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35542. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35543. };
  35544. /**
  35545. * Processes to execute after binding the material to a mesh
  35546. * @param mesh defines the rendered mesh
  35547. */
  35548. Material.prototype._afterBind = function (mesh) {
  35549. this._scene._cachedMaterial = this;
  35550. if (mesh) {
  35551. this._scene._cachedVisibility = mesh.visibility;
  35552. }
  35553. else {
  35554. this._scene._cachedVisibility = 1;
  35555. }
  35556. if (mesh) {
  35557. this.onBindObservable.notifyObservers(mesh);
  35558. }
  35559. if (this.disableDepthWrite) {
  35560. var engine = this._scene.getEngine();
  35561. this._cachedDepthWriteState = engine.getDepthWrite();
  35562. engine.setDepthWrite(false);
  35563. }
  35564. };
  35565. /**
  35566. * Unbinds the material from the mesh
  35567. */
  35568. Material.prototype.unbind = function () {
  35569. this.onUnBindObservable.notifyObservers(this);
  35570. if (this.disableDepthWrite) {
  35571. var engine = this._scene.getEngine();
  35572. engine.setDepthWrite(this._cachedDepthWriteState);
  35573. }
  35574. };
  35575. /**
  35576. * Gets the active textures from the material
  35577. * @returns an array of textures
  35578. */
  35579. Material.prototype.getActiveTextures = function () {
  35580. return [];
  35581. };
  35582. /**
  35583. * Specifies if the material uses a texture
  35584. * @param texture defines the texture to check against the material
  35585. * @returns a boolean specifying if the material uses the texture
  35586. */
  35587. Material.prototype.hasTexture = function (texture) {
  35588. return false;
  35589. };
  35590. /**
  35591. * Makes a duplicate of the material, and gives it a new name
  35592. * @param name defines the new name for the duplicated material
  35593. * @returns the cloned material
  35594. */
  35595. Material.prototype.clone = function (name) {
  35596. return null;
  35597. };
  35598. /**
  35599. * Gets the meshes bound to the material
  35600. * @returns an array of meshes bound to the material
  35601. */
  35602. Material.prototype.getBindedMeshes = function () {
  35603. var result = new Array();
  35604. for (var index = 0; index < this._scene.meshes.length; index++) {
  35605. var mesh = this._scene.meshes[index];
  35606. if (mesh.material === this) {
  35607. result.push(mesh);
  35608. }
  35609. }
  35610. return result;
  35611. };
  35612. /**
  35613. * Force shader compilation
  35614. * @param mesh defines the mesh associated with this material
  35615. * @param onCompiled defines a function to execute once the material is compiled
  35616. * @param options defines the options to configure the compilation
  35617. */
  35618. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35619. var _this = this;
  35620. var localOptions = __assign({ clipPlane: false }, options);
  35621. var subMesh = new BABYLON.BaseSubMesh();
  35622. var scene = this.getScene();
  35623. var checkReady = function () {
  35624. if (!_this._scene || !_this._scene.getEngine()) {
  35625. return;
  35626. }
  35627. if (subMesh._materialDefines) {
  35628. subMesh._materialDefines._renderId = -1;
  35629. }
  35630. var clipPlaneState = scene.clipPlane;
  35631. if (localOptions.clipPlane) {
  35632. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35633. }
  35634. if (_this.storeEffectOnSubMeshes) {
  35635. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35636. if (onCompiled) {
  35637. onCompiled(_this);
  35638. }
  35639. }
  35640. else {
  35641. setTimeout(checkReady, 16);
  35642. }
  35643. }
  35644. else {
  35645. if (_this.isReady(mesh)) {
  35646. if (onCompiled) {
  35647. onCompiled(_this);
  35648. }
  35649. }
  35650. else {
  35651. setTimeout(checkReady, 16);
  35652. }
  35653. }
  35654. if (localOptions.clipPlane) {
  35655. scene.clipPlane = clipPlaneState;
  35656. }
  35657. };
  35658. checkReady();
  35659. };
  35660. /**
  35661. * Force shader compilation
  35662. * @param mesh defines the mesh that will use this material
  35663. * @param options defines additional options for compiling the shaders
  35664. * @returns a promise that resolves when the compilation completes
  35665. */
  35666. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35667. var _this = this;
  35668. return new Promise(function (resolve) {
  35669. _this.forceCompilation(mesh, function () {
  35670. resolve();
  35671. }, options);
  35672. });
  35673. };
  35674. /**
  35675. * Marks a define in the material to indicate that it needs to be re-computed
  35676. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35677. */
  35678. Material.prototype.markAsDirty = function (flag) {
  35679. if (flag & Material.TextureDirtyFlag) {
  35680. this._markAllSubMeshesAsTexturesDirty();
  35681. }
  35682. if (flag & Material.LightDirtyFlag) {
  35683. this._markAllSubMeshesAsLightsDirty();
  35684. }
  35685. if (flag & Material.FresnelDirtyFlag) {
  35686. this._markAllSubMeshesAsFresnelDirty();
  35687. }
  35688. if (flag & Material.AttributesDirtyFlag) {
  35689. this._markAllSubMeshesAsAttributesDirty();
  35690. }
  35691. if (flag & Material.MiscDirtyFlag) {
  35692. this._markAllSubMeshesAsMiscDirty();
  35693. }
  35694. this.getScene().resetCachedMaterial();
  35695. };
  35696. /**
  35697. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35698. * @param func defines a function which checks material defines against the submeshes
  35699. */
  35700. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35701. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35702. var mesh = _a[_i];
  35703. if (!mesh.subMeshes) {
  35704. continue;
  35705. }
  35706. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35707. var subMesh = _c[_b];
  35708. if (subMesh.getMaterial() !== this) {
  35709. continue;
  35710. }
  35711. if (!subMesh._materialDefines) {
  35712. continue;
  35713. }
  35714. func(subMesh._materialDefines);
  35715. }
  35716. }
  35717. };
  35718. /**
  35719. * Indicates that image processing needs to be re-calculated for all submeshes
  35720. */
  35721. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35722. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35723. };
  35724. /**
  35725. * Indicates that textures need to be re-calculated for all submeshes
  35726. */
  35727. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35728. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35729. };
  35730. /**
  35731. * Indicates that fresnel needs to be re-calculated for all submeshes
  35732. */
  35733. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35734. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35735. };
  35736. /**
  35737. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35738. */
  35739. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35740. this._markAllSubMeshesAsDirty(function (defines) {
  35741. defines.markAsFresnelDirty();
  35742. defines.markAsMiscDirty();
  35743. });
  35744. };
  35745. /**
  35746. * Indicates that lights need to be re-calculated for all submeshes
  35747. */
  35748. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35749. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35750. };
  35751. /**
  35752. * Indicates that attributes need to be re-calculated for all submeshes
  35753. */
  35754. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35755. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35756. };
  35757. /**
  35758. * Indicates that misc needs to be re-calculated for all submeshes
  35759. */
  35760. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35761. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35762. };
  35763. /**
  35764. * Indicates that textures and misc need to be re-calculated for all submeshes
  35765. */
  35766. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35767. this._markAllSubMeshesAsDirty(function (defines) {
  35768. defines.markAsTexturesDirty();
  35769. defines.markAsMiscDirty();
  35770. });
  35771. };
  35772. /**
  35773. * Disposes the material
  35774. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35775. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35776. */
  35777. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35778. // Animations
  35779. this.getScene().stopAnimation(this);
  35780. this.getScene().freeProcessedMaterials();
  35781. // Remove from scene
  35782. var index = this._scene.materials.indexOf(this);
  35783. if (index >= 0) {
  35784. this._scene.materials.splice(index, 1);
  35785. }
  35786. // Remove from meshes
  35787. for (index = 0; index < this._scene.meshes.length; index++) {
  35788. var mesh = this._scene.meshes[index];
  35789. if (mesh.material === this) {
  35790. mesh.material = null;
  35791. if (mesh.geometry) {
  35792. var geometry = (mesh.geometry);
  35793. if (this.storeEffectOnSubMeshes) {
  35794. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35795. var subMesh = _a[_i];
  35796. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35797. if (forceDisposeEffect && subMesh._materialEffect) {
  35798. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35799. }
  35800. }
  35801. }
  35802. else {
  35803. geometry._releaseVertexArrayObject(this._effect);
  35804. }
  35805. }
  35806. }
  35807. }
  35808. this._uniformBuffer.dispose();
  35809. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35810. if (forceDisposeEffect && this._effect) {
  35811. if (!this.storeEffectOnSubMeshes) {
  35812. this._scene.getEngine()._releaseEffect(this._effect);
  35813. }
  35814. this._effect = null;
  35815. }
  35816. // Callback
  35817. this.onDisposeObservable.notifyObservers(this);
  35818. this.onDisposeObservable.clear();
  35819. this.onBindObservable.clear();
  35820. this.onUnBindObservable.clear();
  35821. };
  35822. /**
  35823. * Serializes this material
  35824. * @returns the serialized material object
  35825. */
  35826. Material.prototype.serialize = function () {
  35827. return BABYLON.SerializationHelper.Serialize(this);
  35828. };
  35829. /**
  35830. * Creates a MultiMaterial from parsed MultiMaterial data.
  35831. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35832. * @param scene defines the hosting scene
  35833. * @returns a new MultiMaterial
  35834. */
  35835. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35836. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35837. multiMaterial.id = parsedMultiMaterial.id;
  35838. if (BABYLON.Tags) {
  35839. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35840. }
  35841. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35842. var subMatId = parsedMultiMaterial.materials[matIndex];
  35843. if (subMatId) {
  35844. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35845. }
  35846. else {
  35847. multiMaterial.subMaterials.push(null);
  35848. }
  35849. }
  35850. return multiMaterial;
  35851. };
  35852. /**
  35853. * Creates a material from parsed material data
  35854. * @param parsedMaterial defines parsed material data
  35855. * @param scene defines the hosting scene
  35856. * @param rootUrl defines the root URL to use to load textures
  35857. * @returns a new material
  35858. */
  35859. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35860. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35861. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35862. }
  35863. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35864. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35865. if (!BABYLON.LegacyPBRMaterial) {
  35866. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35867. return;
  35868. }
  35869. }
  35870. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35871. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35872. };
  35873. // Triangle views
  35874. Material._TriangleFillMode = 0;
  35875. Material._WireFrameFillMode = 1;
  35876. Material._PointFillMode = 2;
  35877. // Draw modes
  35878. Material._PointListDrawMode = 3;
  35879. Material._LineListDrawMode = 4;
  35880. Material._LineLoopDrawMode = 5;
  35881. Material._LineStripDrawMode = 6;
  35882. Material._TriangleStripDrawMode = 7;
  35883. Material._TriangleFanDrawMode = 8;
  35884. /**
  35885. * Stores the clock-wise side orientation
  35886. */
  35887. Material._ClockWiseSideOrientation = 0;
  35888. /**
  35889. * Stores the counter clock-wise side orientation
  35890. */
  35891. Material._CounterClockWiseSideOrientation = 1;
  35892. /**
  35893. * The dirty texture flag value
  35894. */
  35895. Material._TextureDirtyFlag = 1;
  35896. /**
  35897. * The dirty light flag value
  35898. */
  35899. Material._LightDirtyFlag = 2;
  35900. /**
  35901. * The dirty fresnel flag value
  35902. */
  35903. Material._FresnelDirtyFlag = 4;
  35904. /**
  35905. * The dirty attribute flag value
  35906. */
  35907. Material._AttributesDirtyFlag = 8;
  35908. /**
  35909. * The dirty misc flag value
  35910. */
  35911. Material._MiscDirtyFlag = 16;
  35912. __decorate([
  35913. BABYLON.serialize()
  35914. ], Material.prototype, "id", void 0);
  35915. __decorate([
  35916. BABYLON.serialize()
  35917. ], Material.prototype, "uniqueId", void 0);
  35918. __decorate([
  35919. BABYLON.serialize()
  35920. ], Material.prototype, "name", void 0);
  35921. __decorate([
  35922. BABYLON.serialize()
  35923. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35924. __decorate([
  35925. BABYLON.serialize()
  35926. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35927. __decorate([
  35928. BABYLON.serialize()
  35929. ], Material.prototype, "state", void 0);
  35930. __decorate([
  35931. BABYLON.serialize("alpha")
  35932. ], Material.prototype, "_alpha", void 0);
  35933. __decorate([
  35934. BABYLON.serialize("backFaceCulling")
  35935. ], Material.prototype, "_backFaceCulling", void 0);
  35936. __decorate([
  35937. BABYLON.serialize()
  35938. ], Material.prototype, "sideOrientation", void 0);
  35939. __decorate([
  35940. BABYLON.serialize("alphaMode")
  35941. ], Material.prototype, "_alphaMode", void 0);
  35942. __decorate([
  35943. BABYLON.serialize()
  35944. ], Material.prototype, "_needDepthPrePass", void 0);
  35945. __decorate([
  35946. BABYLON.serialize()
  35947. ], Material.prototype, "disableDepthWrite", void 0);
  35948. __decorate([
  35949. BABYLON.serialize()
  35950. ], Material.prototype, "forceDepthWrite", void 0);
  35951. __decorate([
  35952. BABYLON.serialize()
  35953. ], Material.prototype, "separateCullingPass", void 0);
  35954. __decorate([
  35955. BABYLON.serialize("fogEnabled")
  35956. ], Material.prototype, "_fogEnabled", void 0);
  35957. __decorate([
  35958. BABYLON.serialize()
  35959. ], Material.prototype, "pointSize", void 0);
  35960. __decorate([
  35961. BABYLON.serialize()
  35962. ], Material.prototype, "zOffset", void 0);
  35963. __decorate([
  35964. BABYLON.serialize()
  35965. ], Material.prototype, "wireframe", null);
  35966. __decorate([
  35967. BABYLON.serialize()
  35968. ], Material.prototype, "pointsCloud", null);
  35969. __decorate([
  35970. BABYLON.serialize()
  35971. ], Material.prototype, "fillMode", null);
  35972. return Material;
  35973. }());
  35974. BABYLON.Material = Material;
  35975. })(BABYLON || (BABYLON = {}));
  35976. //# sourceMappingURL=babylon.material.js.map
  35977. var BABYLON;
  35978. (function (BABYLON) {
  35979. var UniformBuffer = /** @class */ (function () {
  35980. /**
  35981. * Uniform buffer objects.
  35982. *
  35983. * Handles blocks of uniform on the GPU.
  35984. *
  35985. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35986. *
  35987. * For more information, please refer to :
  35988. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35989. */
  35990. function UniformBuffer(engine, data, dynamic) {
  35991. this._engine = engine;
  35992. this._noUBO = !engine.supportsUniformBuffers;
  35993. this._dynamic = dynamic;
  35994. this._data = data || [];
  35995. this._uniformLocations = {};
  35996. this._uniformSizes = {};
  35997. this._uniformLocationPointer = 0;
  35998. this._needSync = false;
  35999. if (this._noUBO) {
  36000. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36001. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36002. this.updateFloat = this._updateFloatForEffect;
  36003. this.updateFloat2 = this._updateFloat2ForEffect;
  36004. this.updateFloat3 = this._updateFloat3ForEffect;
  36005. this.updateFloat4 = this._updateFloat4ForEffect;
  36006. this.updateMatrix = this._updateMatrixForEffect;
  36007. this.updateVector3 = this._updateVector3ForEffect;
  36008. this.updateVector4 = this._updateVector4ForEffect;
  36009. this.updateColor3 = this._updateColor3ForEffect;
  36010. this.updateColor4 = this._updateColor4ForEffect;
  36011. }
  36012. else {
  36013. this._engine._uniformBuffers.push(this);
  36014. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36015. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36016. this.updateFloat = this._updateFloatForUniform;
  36017. this.updateFloat2 = this._updateFloat2ForUniform;
  36018. this.updateFloat3 = this._updateFloat3ForUniform;
  36019. this.updateFloat4 = this._updateFloat4ForUniform;
  36020. this.updateMatrix = this._updateMatrixForUniform;
  36021. this.updateVector3 = this._updateVector3ForUniform;
  36022. this.updateVector4 = this._updateVector4ForUniform;
  36023. this.updateColor3 = this._updateColor3ForUniform;
  36024. this.updateColor4 = this._updateColor4ForUniform;
  36025. }
  36026. }
  36027. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36028. // Properties
  36029. /**
  36030. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36031. * or just falling back on setUniformXXX calls.
  36032. */
  36033. get: function () {
  36034. return !this._noUBO;
  36035. },
  36036. enumerable: true,
  36037. configurable: true
  36038. });
  36039. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36040. /**
  36041. * Indicates if the WebGL underlying uniform buffer is in sync
  36042. * with the javascript cache data.
  36043. */
  36044. get: function () {
  36045. return !this._needSync;
  36046. },
  36047. enumerable: true,
  36048. configurable: true
  36049. });
  36050. /**
  36051. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36052. * Also, a dynamic UniformBuffer will disable cache verification and always
  36053. * update the underlying WebGL uniform buffer to the GPU.
  36054. */
  36055. UniformBuffer.prototype.isDynamic = function () {
  36056. return this._dynamic !== undefined;
  36057. };
  36058. /**
  36059. * The data cache on JS side.
  36060. */
  36061. UniformBuffer.prototype.getData = function () {
  36062. return this._bufferData;
  36063. };
  36064. /**
  36065. * The underlying WebGL Uniform buffer.
  36066. */
  36067. UniformBuffer.prototype.getBuffer = function () {
  36068. return this._buffer;
  36069. };
  36070. /**
  36071. * std140 layout specifies how to align data within an UBO structure.
  36072. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36073. * for specs.
  36074. */
  36075. UniformBuffer.prototype._fillAlignment = function (size) {
  36076. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36077. // and 4x4 matrices
  36078. // TODO : change if other types are used
  36079. var alignment;
  36080. if (size <= 2) {
  36081. alignment = size;
  36082. }
  36083. else {
  36084. alignment = 4;
  36085. }
  36086. if ((this._uniformLocationPointer % alignment) !== 0) {
  36087. var oldPointer = this._uniformLocationPointer;
  36088. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36089. var diff = this._uniformLocationPointer - oldPointer;
  36090. for (var i = 0; i < diff; i++) {
  36091. this._data.push(0);
  36092. }
  36093. }
  36094. };
  36095. /**
  36096. * Adds an uniform in the buffer.
  36097. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36098. * for the layout to be correct !
  36099. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36100. * @param {number|number[]} size Data size, or data directly.
  36101. */
  36102. UniformBuffer.prototype.addUniform = function (name, size) {
  36103. if (this._noUBO) {
  36104. return;
  36105. }
  36106. if (this._uniformLocations[name] !== undefined) {
  36107. // Already existing uniform
  36108. return;
  36109. }
  36110. // This function must be called in the order of the shader layout !
  36111. // size can be the size of the uniform, or data directly
  36112. var data;
  36113. if (size instanceof Array) {
  36114. data = size;
  36115. size = data.length;
  36116. }
  36117. else {
  36118. size = size;
  36119. data = [];
  36120. // Fill with zeros
  36121. for (var i = 0; i < size; i++) {
  36122. data.push(0);
  36123. }
  36124. }
  36125. this._fillAlignment(size);
  36126. this._uniformSizes[name] = size;
  36127. this._uniformLocations[name] = this._uniformLocationPointer;
  36128. this._uniformLocationPointer += size;
  36129. for (var i = 0; i < size; i++) {
  36130. this._data.push(data[i]);
  36131. }
  36132. this._needSync = true;
  36133. };
  36134. /**
  36135. * Wrapper for addUniform.
  36136. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36137. * @param {Matrix} mat A 4x4 matrix.
  36138. */
  36139. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36140. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36141. };
  36142. /**
  36143. * Wrapper for addUniform.
  36144. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36145. * @param {number} x
  36146. * @param {number} y
  36147. */
  36148. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36149. var temp = [x, y];
  36150. this.addUniform(name, temp);
  36151. };
  36152. /**
  36153. * Wrapper for addUniform.
  36154. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36155. * @param {number} x
  36156. * @param {number} y
  36157. * @param {number} z
  36158. */
  36159. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36160. var temp = [x, y, z];
  36161. this.addUniform(name, temp);
  36162. };
  36163. /**
  36164. * Wrapper for addUniform.
  36165. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36166. * @param {Color3} color
  36167. */
  36168. UniformBuffer.prototype.addColor3 = function (name, color) {
  36169. var temp = new Array();
  36170. color.toArray(temp);
  36171. this.addUniform(name, temp);
  36172. };
  36173. /**
  36174. * Wrapper for addUniform.
  36175. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36176. * @param {Color3} color
  36177. * @param {number} alpha
  36178. */
  36179. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36180. var temp = new Array();
  36181. color.toArray(temp);
  36182. temp.push(alpha);
  36183. this.addUniform(name, temp);
  36184. };
  36185. /**
  36186. * Wrapper for addUniform.
  36187. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36188. * @param {Vector3} vector
  36189. */
  36190. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36191. var temp = new Array();
  36192. vector.toArray(temp);
  36193. this.addUniform(name, temp);
  36194. };
  36195. /**
  36196. * Wrapper for addUniform.
  36197. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36198. */
  36199. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36200. this.addUniform(name, 12);
  36201. };
  36202. /**
  36203. * Wrapper for addUniform.
  36204. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36205. */
  36206. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36207. this.addUniform(name, 8);
  36208. };
  36209. /**
  36210. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36211. */
  36212. UniformBuffer.prototype.create = function () {
  36213. if (this._noUBO) {
  36214. return;
  36215. }
  36216. if (this._buffer) {
  36217. return; // nothing to do
  36218. }
  36219. // See spec, alignment must be filled as a vec4
  36220. this._fillAlignment(4);
  36221. this._bufferData = new Float32Array(this._data);
  36222. this._rebuild();
  36223. this._needSync = true;
  36224. };
  36225. UniformBuffer.prototype._rebuild = function () {
  36226. if (this._noUBO) {
  36227. return;
  36228. }
  36229. if (this._dynamic) {
  36230. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36231. }
  36232. else {
  36233. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36234. }
  36235. };
  36236. /**
  36237. * Updates the WebGL Uniform Buffer on the GPU.
  36238. * If the `dynamic` flag is set to true, no cache comparison is done.
  36239. * Otherwise, the buffer will be updated only if the cache differs.
  36240. */
  36241. UniformBuffer.prototype.update = function () {
  36242. if (!this._buffer) {
  36243. this.create();
  36244. return;
  36245. }
  36246. if (!this._dynamic && !this._needSync) {
  36247. return;
  36248. }
  36249. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36250. this._needSync = false;
  36251. };
  36252. /**
  36253. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36254. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36255. * @param {number[]|Float32Array} data Flattened data
  36256. * @param {number} size Size of the data.
  36257. */
  36258. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36259. var location = this._uniformLocations[uniformName];
  36260. if (location === undefined) {
  36261. if (this._buffer) {
  36262. // Cannot add an uniform if the buffer is already created
  36263. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36264. return;
  36265. }
  36266. this.addUniform(uniformName, size);
  36267. location = this._uniformLocations[uniformName];
  36268. }
  36269. if (!this._buffer) {
  36270. this.create();
  36271. }
  36272. if (!this._dynamic) {
  36273. // Cache for static uniform buffers
  36274. var changed = false;
  36275. for (var i = 0; i < size; i++) {
  36276. if (this._bufferData[location + i] !== data[i]) {
  36277. changed = true;
  36278. this._bufferData[location + i] = data[i];
  36279. }
  36280. }
  36281. this._needSync = this._needSync || changed;
  36282. }
  36283. else {
  36284. // No cache for dynamic
  36285. for (var i = 0; i < size; i++) {
  36286. this._bufferData[location + i] = data[i];
  36287. }
  36288. }
  36289. };
  36290. // Update methods
  36291. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36292. // To match std140, matrix must be realigned
  36293. for (var i = 0; i < 3; i++) {
  36294. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36295. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36296. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36297. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36298. }
  36299. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36300. };
  36301. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36302. this._currentEffect.setMatrix3x3(name, matrix);
  36303. };
  36304. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36305. this._currentEffect.setMatrix2x2(name, matrix);
  36306. };
  36307. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36308. // To match std140, matrix must be realigned
  36309. for (var i = 0; i < 2; i++) {
  36310. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36311. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36312. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36313. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36314. }
  36315. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36316. };
  36317. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36318. this._currentEffect.setFloat(name, x);
  36319. };
  36320. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36321. UniformBuffer._tempBuffer[0] = x;
  36322. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36323. };
  36324. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36325. if (suffix === void 0) { suffix = ""; }
  36326. this._currentEffect.setFloat2(name + suffix, x, y);
  36327. };
  36328. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36329. if (suffix === void 0) { suffix = ""; }
  36330. UniformBuffer._tempBuffer[0] = x;
  36331. UniformBuffer._tempBuffer[1] = y;
  36332. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36333. };
  36334. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36335. if (suffix === void 0) { suffix = ""; }
  36336. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36337. };
  36338. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36339. if (suffix === void 0) { suffix = ""; }
  36340. UniformBuffer._tempBuffer[0] = x;
  36341. UniformBuffer._tempBuffer[1] = y;
  36342. UniformBuffer._tempBuffer[2] = z;
  36343. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36344. };
  36345. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36346. if (suffix === void 0) { suffix = ""; }
  36347. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36348. };
  36349. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36350. if (suffix === void 0) { suffix = ""; }
  36351. UniformBuffer._tempBuffer[0] = x;
  36352. UniformBuffer._tempBuffer[1] = y;
  36353. UniformBuffer._tempBuffer[2] = z;
  36354. UniformBuffer._tempBuffer[3] = w;
  36355. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36356. };
  36357. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36358. this._currentEffect.setMatrix(name, mat);
  36359. };
  36360. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36361. this.updateUniform(name, mat.toArray(), 16);
  36362. };
  36363. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36364. this._currentEffect.setVector3(name, vector);
  36365. };
  36366. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36367. vector.toArray(UniformBuffer._tempBuffer);
  36368. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36369. };
  36370. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36371. this._currentEffect.setVector4(name, vector);
  36372. };
  36373. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36374. vector.toArray(UniformBuffer._tempBuffer);
  36375. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36376. };
  36377. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36378. if (suffix === void 0) { suffix = ""; }
  36379. this._currentEffect.setColor3(name + suffix, color);
  36380. };
  36381. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36382. if (suffix === void 0) { suffix = ""; }
  36383. color.toArray(UniformBuffer._tempBuffer);
  36384. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36385. };
  36386. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36387. if (suffix === void 0) { suffix = ""; }
  36388. this._currentEffect.setColor4(name + suffix, color, alpha);
  36389. };
  36390. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36391. if (suffix === void 0) { suffix = ""; }
  36392. color.toArray(UniformBuffer._tempBuffer);
  36393. UniformBuffer._tempBuffer[3] = alpha;
  36394. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36395. };
  36396. /**
  36397. * Sets a sampler uniform on the effect.
  36398. * @param {string} name Name of the sampler.
  36399. * @param {Texture} texture
  36400. */
  36401. UniformBuffer.prototype.setTexture = function (name, texture) {
  36402. this._currentEffect.setTexture(name, texture);
  36403. };
  36404. /**
  36405. * Directly updates the value of the uniform in the cache AND on the GPU.
  36406. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36407. * @param {number[]|Float32Array} data Flattened data
  36408. */
  36409. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36410. this.updateUniform(uniformName, data, data.length);
  36411. this.update();
  36412. };
  36413. /**
  36414. * Binds this uniform buffer to an effect.
  36415. * @param {Effect} effect
  36416. * @param {string} name Name of the uniform block in the shader.
  36417. */
  36418. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36419. this._currentEffect = effect;
  36420. if (this._noUBO || !this._buffer) {
  36421. return;
  36422. }
  36423. effect.bindUniformBuffer(this._buffer, name);
  36424. };
  36425. /**
  36426. * Disposes the uniform buffer.
  36427. */
  36428. UniformBuffer.prototype.dispose = function () {
  36429. if (this._noUBO) {
  36430. return;
  36431. }
  36432. var index = this._engine._uniformBuffers.indexOf(this);
  36433. if (index !== -1) {
  36434. this._engine._uniformBuffers.splice(index, 1);
  36435. }
  36436. if (!this._buffer) {
  36437. return;
  36438. }
  36439. if (this._engine._releaseBuffer(this._buffer)) {
  36440. this._buffer = null;
  36441. }
  36442. };
  36443. // Pool for avoiding memory leaks
  36444. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36445. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36446. return UniformBuffer;
  36447. }());
  36448. BABYLON.UniformBuffer = UniformBuffer;
  36449. })(BABYLON || (BABYLON = {}));
  36450. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36451. var BABYLON;
  36452. (function (BABYLON) {
  36453. /**
  36454. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36455. */
  36456. var VertexData = /** @class */ (function () {
  36457. function VertexData() {
  36458. }
  36459. /**
  36460. * Uses the passed data array to set the set the values for the specified kind of data
  36461. * @param data a linear array of floating numbers
  36462. * @param kind the type of data that is being set, eg positions, colors etc
  36463. */
  36464. VertexData.prototype.set = function (data, kind) {
  36465. switch (kind) {
  36466. case BABYLON.VertexBuffer.PositionKind:
  36467. this.positions = data;
  36468. break;
  36469. case BABYLON.VertexBuffer.NormalKind:
  36470. this.normals = data;
  36471. break;
  36472. case BABYLON.VertexBuffer.TangentKind:
  36473. this.tangents = data;
  36474. break;
  36475. case BABYLON.VertexBuffer.UVKind:
  36476. this.uvs = data;
  36477. break;
  36478. case BABYLON.VertexBuffer.UV2Kind:
  36479. this.uvs2 = data;
  36480. break;
  36481. case BABYLON.VertexBuffer.UV3Kind:
  36482. this.uvs3 = data;
  36483. break;
  36484. case BABYLON.VertexBuffer.UV4Kind:
  36485. this.uvs4 = data;
  36486. break;
  36487. case BABYLON.VertexBuffer.UV5Kind:
  36488. this.uvs5 = data;
  36489. break;
  36490. case BABYLON.VertexBuffer.UV6Kind:
  36491. this.uvs6 = data;
  36492. break;
  36493. case BABYLON.VertexBuffer.ColorKind:
  36494. this.colors = data;
  36495. break;
  36496. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36497. this.matricesIndices = data;
  36498. break;
  36499. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36500. this.matricesWeights = data;
  36501. break;
  36502. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36503. this.matricesIndicesExtra = data;
  36504. break;
  36505. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36506. this.matricesWeightsExtra = data;
  36507. break;
  36508. }
  36509. };
  36510. /**
  36511. * Associates the vertexData to the passed Mesh.
  36512. * Sets it as updatable or not (default `false`)
  36513. * @param mesh the mesh the vertexData is applied to
  36514. * @param updatable when used and having the value true allows new data to update the vertexData
  36515. * @returns the VertexData
  36516. */
  36517. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36518. this._applyTo(mesh, updatable);
  36519. return this;
  36520. };
  36521. /**
  36522. * Associates the vertexData to the passed Geometry.
  36523. * Sets it as updatable or not (default `false`)
  36524. * @param geometry the geometry the vertexData is applied to
  36525. * @param updatable when used and having the value true allows new data to update the vertexData
  36526. * @returns VertexData
  36527. */
  36528. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36529. this._applyTo(geometry, updatable);
  36530. return this;
  36531. };
  36532. /**
  36533. * Updates the associated mesh
  36534. * @param mesh the mesh to be updated
  36535. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36536. * @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
  36537. * @returns VertexData
  36538. */
  36539. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36540. this._update(mesh);
  36541. return this;
  36542. };
  36543. /**
  36544. * Updates the associated geometry
  36545. * @param geometry the geometry to be updated
  36546. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36547. * @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
  36548. * @returns VertexData.
  36549. */
  36550. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36551. this._update(geometry);
  36552. return this;
  36553. };
  36554. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36555. if (updatable === void 0) { updatable = false; }
  36556. if (this.positions) {
  36557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36558. }
  36559. if (this.normals) {
  36560. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36561. }
  36562. if (this.tangents) {
  36563. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36564. }
  36565. if (this.uvs) {
  36566. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36567. }
  36568. if (this.uvs2) {
  36569. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36570. }
  36571. if (this.uvs3) {
  36572. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36573. }
  36574. if (this.uvs4) {
  36575. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36576. }
  36577. if (this.uvs5) {
  36578. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36579. }
  36580. if (this.uvs6) {
  36581. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36582. }
  36583. if (this.colors) {
  36584. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36585. }
  36586. if (this.matricesIndices) {
  36587. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36588. }
  36589. if (this.matricesWeights) {
  36590. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36591. }
  36592. if (this.matricesIndicesExtra) {
  36593. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36594. }
  36595. if (this.matricesWeightsExtra) {
  36596. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36597. }
  36598. if (this.indices) {
  36599. meshOrGeometry.setIndices(this.indices, null, updatable);
  36600. }
  36601. else {
  36602. meshOrGeometry.setIndices([], null);
  36603. }
  36604. return this;
  36605. };
  36606. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36607. if (this.positions) {
  36608. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36609. }
  36610. if (this.normals) {
  36611. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36612. }
  36613. if (this.tangents) {
  36614. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36615. }
  36616. if (this.uvs) {
  36617. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36618. }
  36619. if (this.uvs2) {
  36620. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36621. }
  36622. if (this.uvs3) {
  36623. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36624. }
  36625. if (this.uvs4) {
  36626. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36627. }
  36628. if (this.uvs5) {
  36629. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36630. }
  36631. if (this.uvs6) {
  36632. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36633. }
  36634. if (this.colors) {
  36635. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36636. }
  36637. if (this.matricesIndices) {
  36638. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36639. }
  36640. if (this.matricesWeights) {
  36641. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36642. }
  36643. if (this.matricesIndicesExtra) {
  36644. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36645. }
  36646. if (this.matricesWeightsExtra) {
  36647. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36648. }
  36649. if (this.indices) {
  36650. meshOrGeometry.setIndices(this.indices, null);
  36651. }
  36652. return this;
  36653. };
  36654. /**
  36655. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36656. * @param matrix the transforming matrix
  36657. * @returns the VertexData
  36658. */
  36659. VertexData.prototype.transform = function (matrix) {
  36660. var transformed = BABYLON.Vector3.Zero();
  36661. var index;
  36662. if (this.positions) {
  36663. var position = BABYLON.Vector3.Zero();
  36664. for (index = 0; index < this.positions.length; index += 3) {
  36665. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36666. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36667. this.positions[index] = transformed.x;
  36668. this.positions[index + 1] = transformed.y;
  36669. this.positions[index + 2] = transformed.z;
  36670. }
  36671. }
  36672. if (this.normals) {
  36673. var normal = BABYLON.Vector3.Zero();
  36674. for (index = 0; index < this.normals.length; index += 3) {
  36675. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36676. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36677. this.normals[index] = transformed.x;
  36678. this.normals[index + 1] = transformed.y;
  36679. this.normals[index + 2] = transformed.z;
  36680. }
  36681. }
  36682. if (this.tangents) {
  36683. var tangent = BABYLON.Vector4.Zero();
  36684. var tangentTransformed = BABYLON.Vector4.Zero();
  36685. for (index = 0; index < this.tangents.length; index += 4) {
  36686. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36687. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36688. this.tangents[index] = tangentTransformed.x;
  36689. this.tangents[index + 1] = tangentTransformed.y;
  36690. this.tangents[index + 2] = tangentTransformed.z;
  36691. this.tangents[index + 3] = tangentTransformed.w;
  36692. }
  36693. }
  36694. return this;
  36695. };
  36696. /**
  36697. * Merges the passed VertexData into the current one
  36698. * @param other the VertexData to be merged into the current one
  36699. * @returns the modified VertexData
  36700. */
  36701. VertexData.prototype.merge = function (other) {
  36702. this._validate();
  36703. other._validate();
  36704. if (!this.normals !== !other.normals ||
  36705. !this.tangents !== !other.tangents ||
  36706. !this.uvs !== !other.uvs ||
  36707. !this.uvs2 !== !other.uvs2 ||
  36708. !this.uvs3 !== !other.uvs3 ||
  36709. !this.uvs4 !== !other.uvs4 ||
  36710. !this.uvs5 !== !other.uvs5 ||
  36711. !this.uvs6 !== !other.uvs6 ||
  36712. !this.colors !== !other.colors ||
  36713. !this.matricesIndices !== !other.matricesIndices ||
  36714. !this.matricesWeights !== !other.matricesWeights ||
  36715. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36716. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36717. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36718. }
  36719. if (other.indices) {
  36720. if (!this.indices) {
  36721. this.indices = [];
  36722. }
  36723. var offset = this.positions ? this.positions.length / 3 : 0;
  36724. for (var index = 0; index < other.indices.length; index++) {
  36725. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36726. this.indices.push(other.indices[index] + offset);
  36727. }
  36728. }
  36729. this.positions = this._mergeElement(this.positions, other.positions);
  36730. this.normals = this._mergeElement(this.normals, other.normals);
  36731. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36732. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36733. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36734. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36735. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36736. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36737. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36738. this.colors = this._mergeElement(this.colors, other.colors);
  36739. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36740. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36741. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36742. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36743. return this;
  36744. };
  36745. VertexData.prototype._mergeElement = function (source, other) {
  36746. if (!source) {
  36747. return other;
  36748. }
  36749. if (!other) {
  36750. return source;
  36751. }
  36752. var len = other.length + source.length;
  36753. var isSrcTypedArray = source instanceof Float32Array;
  36754. var isOthTypedArray = other instanceof Float32Array;
  36755. // use non-loop method when the source is Float32Array
  36756. if (isSrcTypedArray) {
  36757. var ret32 = new Float32Array(len);
  36758. ret32.set(source);
  36759. ret32.set(other, source.length);
  36760. return ret32;
  36761. // source is number[], when other is also use concat
  36762. }
  36763. else if (!isOthTypedArray) {
  36764. return source.concat(other);
  36765. // source is a number[], but other is a Float32Array, loop required
  36766. }
  36767. else {
  36768. var ret = source.slice(0); // copy source to a separate array
  36769. for (var i = 0, len = other.length; i < len; i++) {
  36770. ret.push(other[i]);
  36771. }
  36772. return ret;
  36773. }
  36774. };
  36775. VertexData.prototype._validate = function () {
  36776. if (!this.positions) {
  36777. throw new Error("Positions are required");
  36778. }
  36779. var getElementCount = function (kind, values) {
  36780. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36781. if ((values.length % stride) !== 0) {
  36782. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36783. }
  36784. return values.length / stride;
  36785. };
  36786. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36787. var validateElementCount = function (kind, values) {
  36788. var elementCount = getElementCount(kind, values);
  36789. if (elementCount !== positionsElementCount) {
  36790. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36791. }
  36792. };
  36793. if (this.normals)
  36794. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36795. if (this.tangents)
  36796. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36797. if (this.uvs)
  36798. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36799. if (this.uvs2)
  36800. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36801. if (this.uvs3)
  36802. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36803. if (this.uvs4)
  36804. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36805. if (this.uvs5)
  36806. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36807. if (this.uvs6)
  36808. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36809. if (this.colors)
  36810. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36811. if (this.matricesIndices)
  36812. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36813. if (this.matricesWeights)
  36814. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36815. if (this.matricesIndicesExtra)
  36816. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36817. if (this.matricesWeightsExtra)
  36818. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36819. };
  36820. /**
  36821. * Serializes the VertexData
  36822. * @returns a serialized object
  36823. */
  36824. VertexData.prototype.serialize = function () {
  36825. var serializationObject = this.serialize();
  36826. if (this.positions) {
  36827. serializationObject.positions = this.positions;
  36828. }
  36829. if (this.normals) {
  36830. serializationObject.normals = this.normals;
  36831. }
  36832. if (this.tangents) {
  36833. serializationObject.tangents = this.tangents;
  36834. }
  36835. if (this.uvs) {
  36836. serializationObject.uvs = this.uvs;
  36837. }
  36838. if (this.uvs2) {
  36839. serializationObject.uvs2 = this.uvs2;
  36840. }
  36841. if (this.uvs3) {
  36842. serializationObject.uvs3 = this.uvs3;
  36843. }
  36844. if (this.uvs4) {
  36845. serializationObject.uvs4 = this.uvs4;
  36846. }
  36847. if (this.uvs5) {
  36848. serializationObject.uvs5 = this.uvs5;
  36849. }
  36850. if (this.uvs6) {
  36851. serializationObject.uvs6 = this.uvs6;
  36852. }
  36853. if (this.colors) {
  36854. serializationObject.colors = this.colors;
  36855. }
  36856. if (this.matricesIndices) {
  36857. serializationObject.matricesIndices = this.matricesIndices;
  36858. serializationObject.matricesIndices._isExpanded = true;
  36859. }
  36860. if (this.matricesWeights) {
  36861. serializationObject.matricesWeights = this.matricesWeights;
  36862. }
  36863. if (this.matricesIndicesExtra) {
  36864. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36865. serializationObject.matricesIndicesExtra._isExpanded = true;
  36866. }
  36867. if (this.matricesWeightsExtra) {
  36868. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36869. }
  36870. serializationObject.indices = this.indices;
  36871. return serializationObject;
  36872. };
  36873. // Statics
  36874. /**
  36875. * Extracts the vertexData from a mesh
  36876. * @param mesh the mesh from which to extract the VertexData
  36877. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36878. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36879. * @returns the object VertexData associated to the passed mesh
  36880. */
  36881. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36882. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36883. };
  36884. /**
  36885. * Extracts the vertexData from the geometry
  36886. * @param geometry the geometry from which to extract the VertexData
  36887. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36888. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36889. * @returns the object VertexData associated to the passed mesh
  36890. */
  36891. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36892. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36893. };
  36894. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36895. var result = new VertexData();
  36896. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36897. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36898. }
  36899. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36900. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36901. }
  36902. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36903. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36904. }
  36905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36906. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36907. }
  36908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36909. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36910. }
  36911. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36912. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36913. }
  36914. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36915. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36916. }
  36917. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36918. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36919. }
  36920. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36921. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36922. }
  36923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36924. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36925. }
  36926. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36927. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36928. }
  36929. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36930. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36931. }
  36932. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36933. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36934. }
  36935. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36936. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36937. }
  36938. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36939. return result;
  36940. };
  36941. /**
  36942. * Creates the VertexData for a Ribbon
  36943. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36944. * * pathArray array of paths, each of which an array of successive Vector3
  36945. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36946. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36947. * * 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
  36948. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36949. * * 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)
  36950. * * 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)
  36951. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36952. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36953. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36954. * @returns the VertexData of the ribbon
  36955. */
  36956. VertexData.CreateRibbon = function (options) {
  36957. var pathArray = options.pathArray;
  36958. var closeArray = options.closeArray || false;
  36959. var closePath = options.closePath || false;
  36960. var invertUV = options.invertUV || false;
  36961. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36962. var offset = options.offset || defaultOffset;
  36963. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36964. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36965. var customUV = options.uvs;
  36966. var customColors = options.colors;
  36967. var positions = [];
  36968. var indices = [];
  36969. var normals = [];
  36970. var uvs = [];
  36971. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36972. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36973. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36974. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36975. var minlg; // minimal length among all paths from pathArray
  36976. var lg = []; // array of path lengths : nb of vertex per path
  36977. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36978. var p; // path iterator
  36979. var i; // point iterator
  36980. var j; // point iterator
  36981. // if single path in pathArray
  36982. if (pathArray.length < 2) {
  36983. var ar1 = [];
  36984. var ar2 = [];
  36985. for (i = 0; i < pathArray[0].length - offset; i++) {
  36986. ar1.push(pathArray[0][i]);
  36987. ar2.push(pathArray[0][i + offset]);
  36988. }
  36989. pathArray = [ar1, ar2];
  36990. }
  36991. // positions and horizontal distances (u)
  36992. var idc = 0;
  36993. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36994. var path;
  36995. var l;
  36996. minlg = pathArray[0].length;
  36997. var vectlg;
  36998. var dist;
  36999. for (p = 0; p < pathArray.length; p++) {
  37000. uTotalDistance[p] = 0;
  37001. us[p] = [0];
  37002. path = pathArray[p];
  37003. l = path.length;
  37004. minlg = (minlg < l) ? minlg : l;
  37005. j = 0;
  37006. while (j < l) {
  37007. positions.push(path[j].x, path[j].y, path[j].z);
  37008. if (j > 0) {
  37009. vectlg = path[j].subtract(path[j - 1]).length();
  37010. dist = vectlg + uTotalDistance[p];
  37011. us[p].push(dist);
  37012. uTotalDistance[p] = dist;
  37013. }
  37014. j++;
  37015. }
  37016. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37017. j--;
  37018. positions.push(path[0].x, path[0].y, path[0].z);
  37019. vectlg = path[j].subtract(path[0]).length();
  37020. dist = vectlg + uTotalDistance[p];
  37021. us[p].push(dist);
  37022. uTotalDistance[p] = dist;
  37023. }
  37024. lg[p] = l + closePathCorr;
  37025. idx[p] = idc;
  37026. idc += (l + closePathCorr);
  37027. }
  37028. // vertical distances (v)
  37029. var path1;
  37030. var path2;
  37031. var vertex1 = null;
  37032. var vertex2 = null;
  37033. for (i = 0; i < minlg + closePathCorr; i++) {
  37034. vTotalDistance[i] = 0;
  37035. vs[i] = [0];
  37036. for (p = 0; p < pathArray.length - 1; p++) {
  37037. path1 = pathArray[p];
  37038. path2 = pathArray[p + 1];
  37039. if (i === minlg) { // closePath
  37040. vertex1 = path1[0];
  37041. vertex2 = path2[0];
  37042. }
  37043. else {
  37044. vertex1 = path1[i];
  37045. vertex2 = path2[i];
  37046. }
  37047. vectlg = vertex2.subtract(vertex1).length();
  37048. dist = vectlg + vTotalDistance[i];
  37049. vs[i].push(dist);
  37050. vTotalDistance[i] = dist;
  37051. }
  37052. if (closeArray && vertex2 && vertex1) {
  37053. path1 = pathArray[p];
  37054. path2 = pathArray[0];
  37055. if (i === minlg) { // closePath
  37056. vertex2 = path2[0];
  37057. }
  37058. vectlg = vertex2.subtract(vertex1).length();
  37059. dist = vectlg + vTotalDistance[i];
  37060. vTotalDistance[i] = dist;
  37061. }
  37062. }
  37063. // uvs
  37064. var u;
  37065. var v;
  37066. if (customUV) {
  37067. for (p = 0; p < customUV.length; p++) {
  37068. uvs.push(customUV[p].x, customUV[p].y);
  37069. }
  37070. }
  37071. else {
  37072. for (p = 0; p < pathArray.length; p++) {
  37073. for (i = 0; i < minlg + closePathCorr; i++) {
  37074. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37075. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37076. if (invertUV) {
  37077. uvs.push(v, u);
  37078. }
  37079. else {
  37080. uvs.push(u, v);
  37081. }
  37082. }
  37083. }
  37084. }
  37085. // indices
  37086. p = 0; // path index
  37087. var pi = 0; // positions array index
  37088. var l1 = lg[p] - 1; // path1 length
  37089. var l2 = lg[p + 1] - 1; // path2 length
  37090. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37091. var shft = idx[1] - idx[0]; // shift
  37092. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37093. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37094. // 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
  37095. indices.push(pi, pi + shft, pi + 1);
  37096. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37097. pi += 1;
  37098. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37099. p++;
  37100. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37101. shft = idx[0] - idx[p];
  37102. l1 = lg[p] - 1;
  37103. l2 = lg[0] - 1;
  37104. }
  37105. else {
  37106. shft = idx[p + 1] - idx[p];
  37107. l1 = lg[p] - 1;
  37108. l2 = lg[p + 1] - 1;
  37109. }
  37110. pi = idx[p];
  37111. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37112. }
  37113. }
  37114. // normals
  37115. VertexData.ComputeNormals(positions, indices, normals);
  37116. if (closePath) { // update both the first and last vertex normals to their average value
  37117. var indexFirst = 0;
  37118. var indexLast = 0;
  37119. for (p = 0; p < pathArray.length; p++) {
  37120. indexFirst = idx[p] * 3;
  37121. if (p + 1 < pathArray.length) {
  37122. indexLast = (idx[p + 1] - 1) * 3;
  37123. }
  37124. else {
  37125. indexLast = normals.length - 3;
  37126. }
  37127. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37128. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37129. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37130. normals[indexLast] = normals[indexFirst];
  37131. normals[indexLast + 1] = normals[indexFirst + 1];
  37132. normals[indexLast + 2] = normals[indexFirst + 2];
  37133. }
  37134. }
  37135. // sides
  37136. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37137. // Colors
  37138. var colors = null;
  37139. if (customColors) {
  37140. colors = new Float32Array(customColors.length * 4);
  37141. for (var c = 0; c < customColors.length; c++) {
  37142. colors[c * 4] = customColors[c].r;
  37143. colors[c * 4 + 1] = customColors[c].g;
  37144. colors[c * 4 + 2] = customColors[c].b;
  37145. colors[c * 4 + 3] = customColors[c].a;
  37146. }
  37147. }
  37148. // Result
  37149. var vertexData = new VertexData();
  37150. var positions32 = new Float32Array(positions);
  37151. var normals32 = new Float32Array(normals);
  37152. var uvs32 = new Float32Array(uvs);
  37153. vertexData.indices = indices;
  37154. vertexData.positions = positions32;
  37155. vertexData.normals = normals32;
  37156. vertexData.uvs = uvs32;
  37157. if (colors) {
  37158. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37159. }
  37160. if (closePath) {
  37161. vertexData._idx = idx;
  37162. }
  37163. return vertexData;
  37164. };
  37165. /**
  37166. * Creates the VertexData for a box
  37167. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37168. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37169. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37170. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37171. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37172. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37173. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37174. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37175. * * 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)
  37176. * * 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)
  37177. * @returns the VertexData of the box
  37178. */
  37179. VertexData.CreateBox = function (options) {
  37180. var normalsSource = [
  37181. new BABYLON.Vector3(0, 0, 1),
  37182. new BABYLON.Vector3(0, 0, -1),
  37183. new BABYLON.Vector3(1, 0, 0),
  37184. new BABYLON.Vector3(-1, 0, 0),
  37185. new BABYLON.Vector3(0, 1, 0),
  37186. new BABYLON.Vector3(0, -1, 0)
  37187. ];
  37188. var indices = [];
  37189. var positions = [];
  37190. var normals = [];
  37191. var uvs = [];
  37192. var width = options.width || options.size || 1;
  37193. var height = options.height || options.size || 1;
  37194. var depth = options.depth || options.size || 1;
  37195. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37196. var faceUV = options.faceUV || new Array(6);
  37197. var faceColors = options.faceColors;
  37198. var colors = [];
  37199. // default face colors and UV if undefined
  37200. for (var f = 0; f < 6; f++) {
  37201. if (faceUV[f] === undefined) {
  37202. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37203. }
  37204. if (faceColors && faceColors[f] === undefined) {
  37205. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37206. }
  37207. }
  37208. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37209. // Create each face in turn.
  37210. for (var index = 0; index < normalsSource.length; index++) {
  37211. var normal = normalsSource[index];
  37212. // Get two vectors perpendicular to the face normal and to each other.
  37213. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37214. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37215. // Six indices (two triangles) per face.
  37216. var verticesLength = positions.length / 3;
  37217. indices.push(verticesLength);
  37218. indices.push(verticesLength + 1);
  37219. indices.push(verticesLength + 2);
  37220. indices.push(verticesLength);
  37221. indices.push(verticesLength + 2);
  37222. indices.push(verticesLength + 3);
  37223. // Four vertices per face.
  37224. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37225. positions.push(vertex.x, vertex.y, vertex.z);
  37226. normals.push(normal.x, normal.y, normal.z);
  37227. uvs.push(faceUV[index].z, faceUV[index].w);
  37228. if (faceColors) {
  37229. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37230. }
  37231. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37232. positions.push(vertex.x, vertex.y, vertex.z);
  37233. normals.push(normal.x, normal.y, normal.z);
  37234. uvs.push(faceUV[index].x, faceUV[index].w);
  37235. if (faceColors) {
  37236. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37237. }
  37238. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37239. positions.push(vertex.x, vertex.y, vertex.z);
  37240. normals.push(normal.x, normal.y, normal.z);
  37241. uvs.push(faceUV[index].x, faceUV[index].y);
  37242. if (faceColors) {
  37243. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37244. }
  37245. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37246. positions.push(vertex.x, vertex.y, vertex.z);
  37247. normals.push(normal.x, normal.y, normal.z);
  37248. uvs.push(faceUV[index].z, faceUV[index].y);
  37249. if (faceColors) {
  37250. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37251. }
  37252. }
  37253. // sides
  37254. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37255. // Result
  37256. var vertexData = new VertexData();
  37257. vertexData.indices = indices;
  37258. vertexData.positions = positions;
  37259. vertexData.normals = normals;
  37260. vertexData.uvs = uvs;
  37261. if (faceColors) {
  37262. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37263. vertexData.colors = totalColors;
  37264. }
  37265. return vertexData;
  37266. };
  37267. /**
  37268. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37269. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37270. * * segments sets the number of horizontal strips optional, default 32
  37271. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37272. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37273. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37274. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37275. * * 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
  37276. * * 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
  37277. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37278. * * 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)
  37279. * * 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)
  37280. * @returns the VertexData of the ellipsoid
  37281. */
  37282. VertexData.CreateSphere = function (options) {
  37283. var segments = options.segments || 32;
  37284. var diameterX = options.diameterX || options.diameter || 1;
  37285. var diameterY = options.diameterY || options.diameter || 1;
  37286. var diameterZ = options.diameterZ || options.diameter || 1;
  37287. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37288. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37289. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37290. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37291. var totalZRotationSteps = 2 + segments;
  37292. var totalYRotationSteps = 2 * totalZRotationSteps;
  37293. var indices = [];
  37294. var positions = [];
  37295. var normals = [];
  37296. var uvs = [];
  37297. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37298. var normalizedZ = zRotationStep / totalZRotationSteps;
  37299. var angleZ = normalizedZ * Math.PI * slice;
  37300. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37301. var normalizedY = yRotationStep / totalYRotationSteps;
  37302. var angleY = normalizedY * Math.PI * 2 * arc;
  37303. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37304. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37305. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37306. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37307. var vertex = complete.multiply(radius);
  37308. var normal = complete.divide(radius).normalize();
  37309. positions.push(vertex.x, vertex.y, vertex.z);
  37310. normals.push(normal.x, normal.y, normal.z);
  37311. uvs.push(normalizedY, normalizedZ);
  37312. }
  37313. if (zRotationStep > 0) {
  37314. var verticesCount = positions.length / 3;
  37315. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37316. indices.push((firstIndex));
  37317. indices.push((firstIndex + 1));
  37318. indices.push(firstIndex + totalYRotationSteps + 1);
  37319. indices.push((firstIndex + totalYRotationSteps + 1));
  37320. indices.push((firstIndex + 1));
  37321. indices.push((firstIndex + totalYRotationSteps + 2));
  37322. }
  37323. }
  37324. }
  37325. // Sides
  37326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37327. // Result
  37328. var vertexData = new VertexData();
  37329. vertexData.indices = indices;
  37330. vertexData.positions = positions;
  37331. vertexData.normals = normals;
  37332. vertexData.uvs = uvs;
  37333. return vertexData;
  37334. };
  37335. /**
  37336. * Creates the VertexData for a cylinder, cone or prism
  37337. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37338. * * height sets the height (y direction) of the cylinder, optional, default 2
  37339. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37340. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37341. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37342. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37343. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37344. * * 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
  37345. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37346. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37347. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37348. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37349. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37350. * * 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)
  37351. * * 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)
  37352. * @returns the VertexData of the cylinder, cone or prism
  37353. */
  37354. VertexData.CreateCylinder = function (options) {
  37355. var height = options.height || 2;
  37356. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37357. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37358. var tessellation = options.tessellation || 24;
  37359. var subdivisions = options.subdivisions || 1;
  37360. var hasRings = options.hasRings ? true : false;
  37361. var enclose = options.enclose ? true : false;
  37362. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37363. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37364. var faceUV = options.faceUV || new Array(3);
  37365. var faceColors = options.faceColors;
  37366. // default face colors and UV if undefined
  37367. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37368. var ringNb = (hasRings) ? subdivisions : 1;
  37369. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37370. var f;
  37371. for (f = 0; f < surfaceNb; f++) {
  37372. if (faceColors && faceColors[f] === undefined) {
  37373. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37374. }
  37375. }
  37376. for (f = 0; f < surfaceNb; f++) {
  37377. if (faceUV && faceUV[f] === undefined) {
  37378. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37379. }
  37380. }
  37381. var indices = new Array();
  37382. var positions = new Array();
  37383. var normals = new Array();
  37384. var uvs = new Array();
  37385. var colors = new Array();
  37386. var angle_step = Math.PI * 2 * arc / tessellation;
  37387. var angle;
  37388. var h;
  37389. var radius;
  37390. var tan = (diameterBottom - diameterTop) / 2 / height;
  37391. var ringVertex = BABYLON.Vector3.Zero();
  37392. var ringNormal = BABYLON.Vector3.Zero();
  37393. var ringFirstVertex = BABYLON.Vector3.Zero();
  37394. var ringFirstNormal = BABYLON.Vector3.Zero();
  37395. var quadNormal = BABYLON.Vector3.Zero();
  37396. var Y = BABYLON.Axis.Y;
  37397. // positions, normals, uvs
  37398. var i;
  37399. var j;
  37400. var r;
  37401. var ringIdx = 1;
  37402. var s = 1; // surface index
  37403. var cs = 0;
  37404. var v = 0;
  37405. for (i = 0; i <= subdivisions; i++) {
  37406. h = i / subdivisions;
  37407. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37408. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37409. for (r = 0; r < ringIdx; r++) {
  37410. if (hasRings) {
  37411. s += r;
  37412. }
  37413. if (enclose) {
  37414. s += 2 * r;
  37415. }
  37416. for (j = 0; j <= tessellation; j++) {
  37417. angle = j * angle_step;
  37418. // position
  37419. ringVertex.x = Math.cos(-angle) * radius;
  37420. ringVertex.y = -height / 2 + h * height;
  37421. ringVertex.z = Math.sin(-angle) * radius;
  37422. // normal
  37423. if (diameterTop === 0 && i === subdivisions) {
  37424. // if no top cap, reuse former normals
  37425. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37426. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37427. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37428. }
  37429. else {
  37430. ringNormal.x = ringVertex.x;
  37431. ringNormal.z = ringVertex.z;
  37432. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37433. ringNormal.normalize();
  37434. }
  37435. // keep first ring vertex values for enclose
  37436. if (j === 0) {
  37437. ringFirstVertex.copyFrom(ringVertex);
  37438. ringFirstNormal.copyFrom(ringNormal);
  37439. }
  37440. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37441. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37442. if (hasRings) {
  37443. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37444. }
  37445. else {
  37446. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37447. }
  37448. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37449. if (faceColors) {
  37450. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37451. }
  37452. }
  37453. // if enclose, add four vertices and their dedicated normals
  37454. if (arc !== 1 && enclose) {
  37455. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37456. positions.push(0, ringVertex.y, 0);
  37457. positions.push(0, ringVertex.y, 0);
  37458. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37459. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37460. quadNormal.normalize();
  37461. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37462. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37463. quadNormal.normalize();
  37464. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37465. if (hasRings) {
  37466. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37467. }
  37468. else {
  37469. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37470. }
  37471. uvs.push(faceUV[s + 1].x, v);
  37472. uvs.push(faceUV[s + 1].z, v);
  37473. if (hasRings) {
  37474. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37475. }
  37476. else {
  37477. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37478. }
  37479. uvs.push(faceUV[s + 2].x, v);
  37480. uvs.push(faceUV[s + 2].z, v);
  37481. if (faceColors) {
  37482. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37483. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37484. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37485. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37486. }
  37487. }
  37488. if (cs !== s) {
  37489. cs = s;
  37490. }
  37491. }
  37492. }
  37493. // indices
  37494. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37495. var s;
  37496. i = 0;
  37497. for (s = 0; s < subdivisions; s++) {
  37498. var i0 = 0;
  37499. var i1 = 0;
  37500. var i2 = 0;
  37501. var i3 = 0;
  37502. for (j = 0; j < tessellation; j++) {
  37503. i0 = i * (e + 1) + j;
  37504. i1 = (i + 1) * (e + 1) + j;
  37505. i2 = i * (e + 1) + (j + 1);
  37506. i3 = (i + 1) * (e + 1) + (j + 1);
  37507. indices.push(i0, i1, i2);
  37508. indices.push(i3, i2, i1);
  37509. }
  37510. if (arc !== 1 && enclose) { // if enclose, add two quads
  37511. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37512. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37513. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37514. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37515. }
  37516. i = (hasRings) ? (i + 2) : (i + 1);
  37517. }
  37518. // Caps
  37519. var createCylinderCap = function (isTop) {
  37520. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37521. if (radius === 0) {
  37522. return;
  37523. }
  37524. // Cap positions, normals & uvs
  37525. var angle;
  37526. var circleVector;
  37527. var i;
  37528. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37529. var c = null;
  37530. if (faceColors) {
  37531. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37532. }
  37533. // cap center
  37534. var vbase = positions.length / 3;
  37535. var offset = isTop ? height / 2 : -height / 2;
  37536. var center = new BABYLON.Vector3(0, offset, 0);
  37537. positions.push(center.x, center.y, center.z);
  37538. normals.push(0, isTop ? 1 : -1, 0);
  37539. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37540. if (c) {
  37541. colors.push(c.r, c.g, c.b, c.a);
  37542. }
  37543. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37544. for (i = 0; i <= tessellation; i++) {
  37545. angle = Math.PI * 2 * i * arc / tessellation;
  37546. var cos = Math.cos(-angle);
  37547. var sin = Math.sin(-angle);
  37548. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37549. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37550. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37551. normals.push(0, isTop ? 1 : -1, 0);
  37552. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37553. if (c) {
  37554. colors.push(c.r, c.g, c.b, c.a);
  37555. }
  37556. }
  37557. // Cap indices
  37558. for (i = 0; i < tessellation; i++) {
  37559. if (!isTop) {
  37560. indices.push(vbase);
  37561. indices.push(vbase + (i + 1));
  37562. indices.push(vbase + (i + 2));
  37563. }
  37564. else {
  37565. indices.push(vbase);
  37566. indices.push(vbase + (i + 2));
  37567. indices.push(vbase + (i + 1));
  37568. }
  37569. }
  37570. };
  37571. // add caps to geometry
  37572. createCylinderCap(false);
  37573. createCylinderCap(true);
  37574. // Sides
  37575. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37576. var vertexData = new VertexData();
  37577. vertexData.indices = indices;
  37578. vertexData.positions = positions;
  37579. vertexData.normals = normals;
  37580. vertexData.uvs = uvs;
  37581. if (faceColors) {
  37582. vertexData.colors = colors;
  37583. }
  37584. return vertexData;
  37585. };
  37586. /**
  37587. * Creates the VertexData for a torus
  37588. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37589. * * diameter the diameter of the torus, optional default 1
  37590. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37591. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37592. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37593. * * 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)
  37594. * * 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)
  37595. * @returns the VertexData of the torus
  37596. */
  37597. VertexData.CreateTorus = function (options) {
  37598. var indices = [];
  37599. var positions = [];
  37600. var normals = [];
  37601. var uvs = [];
  37602. var diameter = options.diameter || 1;
  37603. var thickness = options.thickness || 0.5;
  37604. var tessellation = options.tessellation || 16;
  37605. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37606. var stride = tessellation + 1;
  37607. for (var i = 0; i <= tessellation; i++) {
  37608. var u = i / tessellation;
  37609. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37610. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37611. for (var j = 0; j <= tessellation; j++) {
  37612. var v = 1 - j / tessellation;
  37613. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37614. var dx = Math.cos(innerAngle);
  37615. var dy = Math.sin(innerAngle);
  37616. // Create a vertex.
  37617. var normal = new BABYLON.Vector3(dx, dy, 0);
  37618. var position = normal.scale(thickness / 2);
  37619. var textureCoordinate = new BABYLON.Vector2(u, v);
  37620. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37621. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37622. positions.push(position.x, position.y, position.z);
  37623. normals.push(normal.x, normal.y, normal.z);
  37624. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37625. // And create indices for two triangles.
  37626. var nextI = (i + 1) % stride;
  37627. var nextJ = (j + 1) % stride;
  37628. indices.push(i * stride + j);
  37629. indices.push(i * stride + nextJ);
  37630. indices.push(nextI * stride + j);
  37631. indices.push(i * stride + nextJ);
  37632. indices.push(nextI * stride + nextJ);
  37633. indices.push(nextI * stride + j);
  37634. }
  37635. }
  37636. // Sides
  37637. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37638. // Result
  37639. var vertexData = new VertexData();
  37640. vertexData.indices = indices;
  37641. vertexData.positions = positions;
  37642. vertexData.normals = normals;
  37643. vertexData.uvs = uvs;
  37644. return vertexData;
  37645. };
  37646. /**
  37647. * Creates the VertexData of the LineSystem
  37648. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37649. * - lines an array of lines, each line being an array of successive Vector3
  37650. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37651. * @returns the VertexData of the LineSystem
  37652. */
  37653. VertexData.CreateLineSystem = function (options) {
  37654. var indices = [];
  37655. var positions = [];
  37656. var lines = options.lines;
  37657. var colors = options.colors;
  37658. var vertexColors = [];
  37659. var idx = 0;
  37660. for (var l = 0; l < lines.length; l++) {
  37661. var points = lines[l];
  37662. for (var index = 0; index < points.length; index++) {
  37663. positions.push(points[index].x, points[index].y, points[index].z);
  37664. if (colors) {
  37665. var color = colors[l];
  37666. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37667. }
  37668. if (index > 0) {
  37669. indices.push(idx - 1);
  37670. indices.push(idx);
  37671. }
  37672. idx++;
  37673. }
  37674. }
  37675. var vertexData = new VertexData();
  37676. vertexData.indices = indices;
  37677. vertexData.positions = positions;
  37678. if (colors) {
  37679. vertexData.colors = vertexColors;
  37680. }
  37681. return vertexData;
  37682. };
  37683. /**
  37684. * Create the VertexData for a DashedLines
  37685. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37686. * - points an array successive Vector3
  37687. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37688. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37689. * - dashNb the intended total number of dashes, optional, default 200
  37690. * @returns the VertexData for the DashedLines
  37691. */
  37692. VertexData.CreateDashedLines = function (options) {
  37693. var dashSize = options.dashSize || 3;
  37694. var gapSize = options.gapSize || 1;
  37695. var dashNb = options.dashNb || 200;
  37696. var points = options.points;
  37697. var positions = new Array();
  37698. var indices = new Array();
  37699. var curvect = BABYLON.Vector3.Zero();
  37700. var lg = 0;
  37701. var nb = 0;
  37702. var shft = 0;
  37703. var dashshft = 0;
  37704. var curshft = 0;
  37705. var idx = 0;
  37706. var i = 0;
  37707. for (i = 0; i < points.length - 1; i++) {
  37708. points[i + 1].subtractToRef(points[i], curvect);
  37709. lg += curvect.length();
  37710. }
  37711. shft = lg / dashNb;
  37712. dashshft = dashSize * shft / (dashSize + gapSize);
  37713. for (i = 0; i < points.length - 1; i++) {
  37714. points[i + 1].subtractToRef(points[i], curvect);
  37715. nb = Math.floor(curvect.length() / shft);
  37716. curvect.normalize();
  37717. for (var j = 0; j < nb; j++) {
  37718. curshft = shft * j;
  37719. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37720. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37721. indices.push(idx, idx + 1);
  37722. idx += 2;
  37723. }
  37724. }
  37725. // Result
  37726. var vertexData = new VertexData();
  37727. vertexData.positions = positions;
  37728. vertexData.indices = indices;
  37729. return vertexData;
  37730. };
  37731. /**
  37732. * Creates the VertexData for a Ground
  37733. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37734. * - width the width (x direction) of the ground, optional, default 1
  37735. * - height the height (z direction) of the ground, optional, default 1
  37736. * - subdivisions the number of subdivisions per side, optional, default 1
  37737. * @returns the VertexData of the Ground
  37738. */
  37739. VertexData.CreateGround = function (options) {
  37740. var indices = [];
  37741. var positions = [];
  37742. var normals = [];
  37743. var uvs = [];
  37744. var row, col;
  37745. var width = options.width || 1;
  37746. var height = options.height || 1;
  37747. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37748. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37749. for (row = 0; row <= subdivisionsY; row++) {
  37750. for (col = 0; col <= subdivisionsX; col++) {
  37751. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37752. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37753. positions.push(position.x, position.y, position.z);
  37754. normals.push(normal.x, normal.y, normal.z);
  37755. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37756. }
  37757. }
  37758. for (row = 0; row < subdivisionsY; row++) {
  37759. for (col = 0; col < subdivisionsX; col++) {
  37760. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37761. indices.push(col + 1 + row * (subdivisionsX + 1));
  37762. indices.push(col + row * (subdivisionsX + 1));
  37763. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37764. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37765. indices.push(col + row * (subdivisionsX + 1));
  37766. }
  37767. }
  37768. // Result
  37769. var vertexData = new VertexData();
  37770. vertexData.indices = indices;
  37771. vertexData.positions = positions;
  37772. vertexData.normals = normals;
  37773. vertexData.uvs = uvs;
  37774. return vertexData;
  37775. };
  37776. /**
  37777. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37778. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37779. * * xmin the ground minimum X coordinate, optional, default -1
  37780. * * zmin the ground minimum Z coordinate, optional, default -1
  37781. * * xmax the ground maximum X coordinate, optional, default 1
  37782. * * zmax the ground maximum Z coordinate, optional, default 1
  37783. * * 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}
  37784. * * 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}
  37785. * @returns the VertexData of the TiledGround
  37786. */
  37787. VertexData.CreateTiledGround = function (options) {
  37788. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37789. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37790. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37791. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37792. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37793. var precision = options.precision || { w: 1, h: 1 };
  37794. var indices = new Array();
  37795. var positions = new Array();
  37796. var normals = new Array();
  37797. var uvs = new Array();
  37798. var row, col, tileRow, tileCol;
  37799. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37800. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37801. precision.w = (precision.w < 1) ? 1 : precision.w;
  37802. precision.h = (precision.h < 1) ? 1 : precision.h;
  37803. var tileSize = {
  37804. 'w': (xmax - xmin) / subdivisions.w,
  37805. 'h': (zmax - zmin) / subdivisions.h
  37806. };
  37807. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37808. // Indices
  37809. var base = positions.length / 3;
  37810. var rowLength = precision.w + 1;
  37811. for (row = 0; row < precision.h; row++) {
  37812. for (col = 0; col < precision.w; col++) {
  37813. var square = [
  37814. base + col + row * rowLength,
  37815. base + (col + 1) + row * rowLength,
  37816. base + (col + 1) + (row + 1) * rowLength,
  37817. base + col + (row + 1) * rowLength
  37818. ];
  37819. indices.push(square[1]);
  37820. indices.push(square[2]);
  37821. indices.push(square[3]);
  37822. indices.push(square[0]);
  37823. indices.push(square[1]);
  37824. indices.push(square[3]);
  37825. }
  37826. }
  37827. // Position, normals and uvs
  37828. var position = BABYLON.Vector3.Zero();
  37829. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37830. for (row = 0; row <= precision.h; row++) {
  37831. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37832. for (col = 0; col <= precision.w; col++) {
  37833. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37834. position.y = 0;
  37835. positions.push(position.x, position.y, position.z);
  37836. normals.push(normal.x, normal.y, normal.z);
  37837. uvs.push(col / precision.w, row / precision.h);
  37838. }
  37839. }
  37840. }
  37841. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37842. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37843. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37844. }
  37845. }
  37846. // Result
  37847. var vertexData = new VertexData();
  37848. vertexData.indices = indices;
  37849. vertexData.positions = positions;
  37850. vertexData.normals = normals;
  37851. vertexData.uvs = uvs;
  37852. return vertexData;
  37853. };
  37854. /**
  37855. * Creates the VertexData of the Ground designed from a heightmap
  37856. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37857. * * width the width (x direction) of the ground
  37858. * * height the height (z direction) of the ground
  37859. * * subdivisions the number of subdivisions per side
  37860. * * minHeight the minimum altitude on the ground, optional, default 0
  37861. * * maxHeight the maximum altitude on the ground, optional default 1
  37862. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37863. * * buffer the array holding the image color data
  37864. * * bufferWidth the width of image
  37865. * * bufferHeight the height of image
  37866. * @returns the VertexData of the Ground designed from a heightmap
  37867. */
  37868. VertexData.CreateGroundFromHeightMap = function (options) {
  37869. var indices = [];
  37870. var positions = [];
  37871. var normals = [];
  37872. var uvs = [];
  37873. var row, col;
  37874. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37875. // Vertices
  37876. for (row = 0; row <= options.subdivisions; row++) {
  37877. for (col = 0; col <= options.subdivisions; col++) {
  37878. 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));
  37879. // Compute height
  37880. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37881. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37882. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37883. var r = options.buffer[pos] / 255.0;
  37884. var g = options.buffer[pos + 1] / 255.0;
  37885. var b = options.buffer[pos + 2] / 255.0;
  37886. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37887. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37888. // Add vertex
  37889. positions.push(position.x, position.y, position.z);
  37890. normals.push(0, 0, 0);
  37891. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37892. }
  37893. }
  37894. // Indices
  37895. for (row = 0; row < options.subdivisions; row++) {
  37896. for (col = 0; col < options.subdivisions; col++) {
  37897. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37898. indices.push(col + 1 + row * (options.subdivisions + 1));
  37899. indices.push(col + row * (options.subdivisions + 1));
  37900. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37901. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37902. indices.push(col + row * (options.subdivisions + 1));
  37903. }
  37904. }
  37905. // Normals
  37906. VertexData.ComputeNormals(positions, indices, normals);
  37907. // Result
  37908. var vertexData = new VertexData();
  37909. vertexData.indices = indices;
  37910. vertexData.positions = positions;
  37911. vertexData.normals = normals;
  37912. vertexData.uvs = uvs;
  37913. return vertexData;
  37914. };
  37915. /**
  37916. * Creates the VertexData for a Plane
  37917. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37918. * * size sets the width and height of the plane to the value of size, optional default 1
  37919. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37920. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37921. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37922. * * 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)
  37923. * * 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)
  37924. * @returns the VertexData of the box
  37925. */
  37926. VertexData.CreatePlane = function (options) {
  37927. var indices = [];
  37928. var positions = [];
  37929. var normals = [];
  37930. var uvs = [];
  37931. var width = options.width || options.size || 1;
  37932. var height = options.height || options.size || 1;
  37933. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37934. // Vertices
  37935. var halfWidth = width / 2.0;
  37936. var halfHeight = height / 2.0;
  37937. positions.push(-halfWidth, -halfHeight, 0);
  37938. normals.push(0, 0, -1.0);
  37939. uvs.push(0.0, 0.0);
  37940. positions.push(halfWidth, -halfHeight, 0);
  37941. normals.push(0, 0, -1.0);
  37942. uvs.push(1.0, 0.0);
  37943. positions.push(halfWidth, halfHeight, 0);
  37944. normals.push(0, 0, -1.0);
  37945. uvs.push(1.0, 1.0);
  37946. positions.push(-halfWidth, halfHeight, 0);
  37947. normals.push(0, 0, -1.0);
  37948. uvs.push(0.0, 1.0);
  37949. // Indices
  37950. indices.push(0);
  37951. indices.push(1);
  37952. indices.push(2);
  37953. indices.push(0);
  37954. indices.push(2);
  37955. indices.push(3);
  37956. // Sides
  37957. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37958. // Result
  37959. var vertexData = new VertexData();
  37960. vertexData.indices = indices;
  37961. vertexData.positions = positions;
  37962. vertexData.normals = normals;
  37963. vertexData.uvs = uvs;
  37964. return vertexData;
  37965. };
  37966. /**
  37967. * Creates the VertexData of the Disc or regular Polygon
  37968. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37969. * * radius the radius of the disc, optional default 0.5
  37970. * * tessellation the number of polygon sides, optional, default 64
  37971. * * 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
  37972. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37973. * * 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)
  37974. * * 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)
  37975. * @returns the VertexData of the box
  37976. */
  37977. VertexData.CreateDisc = function (options) {
  37978. var positions = new Array();
  37979. var indices = new Array();
  37980. var normals = new Array();
  37981. var uvs = new Array();
  37982. var radius = options.radius || 0.5;
  37983. var tessellation = options.tessellation || 64;
  37984. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37985. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37986. // positions and uvs
  37987. positions.push(0, 0, 0); // disc center first
  37988. uvs.push(0.5, 0.5);
  37989. var theta = Math.PI * 2 * arc;
  37990. var step = theta / tessellation;
  37991. for (var a = 0; a < theta; a += step) {
  37992. var x = Math.cos(a);
  37993. var y = Math.sin(a);
  37994. var u = (x + 1) / 2;
  37995. var v = (1 - y) / 2;
  37996. positions.push(radius * x, radius * y, 0);
  37997. uvs.push(u, v);
  37998. }
  37999. if (arc === 1) {
  38000. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38001. uvs.push(uvs[2], uvs[3]);
  38002. }
  38003. //indices
  38004. var vertexNb = positions.length / 3;
  38005. for (var i = 1; i < vertexNb - 1; i++) {
  38006. indices.push(i + 1, 0, i);
  38007. }
  38008. // result
  38009. VertexData.ComputeNormals(positions, indices, normals);
  38010. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38011. var vertexData = new VertexData();
  38012. vertexData.indices = indices;
  38013. vertexData.positions = positions;
  38014. vertexData.normals = normals;
  38015. vertexData.uvs = uvs;
  38016. return vertexData;
  38017. };
  38018. /**
  38019. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38020. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38021. * @param polygon a mesh built from polygonTriangulation.build()
  38022. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38023. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38024. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38025. * @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)
  38026. * @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)
  38027. * @returns the VertexData of the Polygon
  38028. */
  38029. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38030. var faceUV = fUV || new Array(3);
  38031. var faceColors = fColors;
  38032. var colors = [];
  38033. // default face colors and UV if undefined
  38034. for (var f = 0; f < 3; f++) {
  38035. if (faceUV[f] === undefined) {
  38036. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38037. }
  38038. if (faceColors && faceColors[f] === undefined) {
  38039. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38040. }
  38041. }
  38042. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38043. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38044. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38045. var indices = polygon.getIndices();
  38046. // set face colours and textures
  38047. var idx = 0;
  38048. var face = 0;
  38049. for (var index = 0; index < normals.length; index += 3) {
  38050. //Edge Face no. 1
  38051. if (Math.abs(normals[index + 1]) < 0.001) {
  38052. face = 1;
  38053. }
  38054. //Top Face no. 0
  38055. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38056. face = 0;
  38057. }
  38058. //Bottom Face no. 2
  38059. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38060. face = 2;
  38061. }
  38062. idx = index / 3;
  38063. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38064. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38065. if (faceColors) {
  38066. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38067. }
  38068. }
  38069. // sides
  38070. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38071. // Result
  38072. var vertexData = new VertexData();
  38073. vertexData.indices = indices;
  38074. vertexData.positions = positions;
  38075. vertexData.normals = normals;
  38076. vertexData.uvs = uvs;
  38077. if (faceColors) {
  38078. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38079. vertexData.colors = totalColors;
  38080. }
  38081. return vertexData;
  38082. };
  38083. /**
  38084. * Creates the VertexData of the IcoSphere
  38085. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38086. * * radius the radius of the IcoSphere, optional default 1
  38087. * * radiusX allows stretching in the x direction, optional, default radius
  38088. * * radiusY allows stretching in the y direction, optional, default radius
  38089. * * radiusZ allows stretching in the z direction, optional, default radius
  38090. * * flat when true creates a flat shaded mesh, optional, default true
  38091. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38092. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38093. * * 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)
  38094. * * 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)
  38095. * @returns the VertexData of the IcoSphere
  38096. */
  38097. VertexData.CreateIcoSphere = function (options) {
  38098. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38099. var radius = options.radius || 1;
  38100. var flat = (options.flat === undefined) ? true : options.flat;
  38101. var subdivisions = options.subdivisions || 4;
  38102. var radiusX = options.radiusX || radius;
  38103. var radiusY = options.radiusY || radius;
  38104. var radiusZ = options.radiusZ || radius;
  38105. var t = (1 + Math.sqrt(5)) / 2;
  38106. // 12 vertex x,y,z
  38107. var ico_vertices = [
  38108. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38109. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38110. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38111. ];
  38112. // index of 3 vertex makes a face of icopshere
  38113. var ico_indices = [
  38114. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38115. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38116. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38117. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38118. ];
  38119. // vertex for uv have aliased position, not for UV
  38120. var vertices_unalias_id = [
  38121. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38122. // vertex alias
  38123. 0,
  38124. 2,
  38125. 3,
  38126. 3,
  38127. 3,
  38128. 4,
  38129. 7,
  38130. 8,
  38131. 9,
  38132. 9,
  38133. 10,
  38134. 11 // 23: B + 12
  38135. ];
  38136. // uv as integer step (not pixels !)
  38137. var ico_vertexuv = [
  38138. 5, 1, 3, 1, 6, 4, 0, 0,
  38139. 5, 3, 4, 2, 2, 2, 4, 0,
  38140. 2, 0, 1, 1, 6, 0, 6, 2,
  38141. // vertex alias (for same vertex on different faces)
  38142. 0, 4,
  38143. 3, 3,
  38144. 4, 4,
  38145. 3, 1,
  38146. 4, 2,
  38147. 4, 4,
  38148. 0, 2,
  38149. 1, 1,
  38150. 2, 2,
  38151. 3, 3,
  38152. 1, 3,
  38153. 2, 4 // 23: B + 12
  38154. ];
  38155. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38156. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38157. // First island of uv mapping
  38158. // v = 4h 3+ 2
  38159. // v = 3h 9+ 4
  38160. // v = 2h 9+ 5 B
  38161. // v = 1h 9 1 0
  38162. // v = 0h 3 8 7 A
  38163. // u = 0 1 2 3 4 5 6 *a
  38164. // Second island of uv mapping
  38165. // v = 4h 0+ B+ 4+
  38166. // v = 3h A+ 2+
  38167. // v = 2h 7+ 6 3+
  38168. // v = 1h 8+ 3+
  38169. // v = 0h
  38170. // u = 0 1 2 3 4 5 6 *a
  38171. // Face layout on texture UV mapping
  38172. // ============
  38173. // \ 4 /\ 16 / ======
  38174. // \ / \ / /\ 11 /
  38175. // \/ 7 \/ / \ /
  38176. // ======= / 10 \/
  38177. // /\ 17 /\ =======
  38178. // / \ / \ \ 15 /\
  38179. // / 8 \/ 12 \ \ / \
  38180. // ============ \/ 6 \
  38181. // \ 18 /\ ============
  38182. // \ / \ \ 5 /\ 0 /
  38183. // \/ 13 \ \ / \ /
  38184. // ======= \/ 1 \/
  38185. // =============
  38186. // /\ 19 /\ 2 /\
  38187. // / \ / \ / \
  38188. // / 14 \/ 9 \/ 3 \
  38189. // ===================
  38190. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38191. var ustep = 138 / 1024;
  38192. var vstep = 239 / 1024;
  38193. var uoffset = 60 / 1024;
  38194. var voffset = 26 / 1024;
  38195. // Second island should have margin, not to touch the first island
  38196. // avoid any borderline artefact in pixel rounding
  38197. var island_u_offset = -40 / 1024;
  38198. var island_v_offset = +20 / 1024;
  38199. // face is either island 0 or 1 :
  38200. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38201. var island = [
  38202. 0, 0, 0, 0, 1,
  38203. 0, 0, 1, 1, 0,
  38204. 0, 0, 1, 1, 0,
  38205. 0, 1, 1, 1, 0 // 15 - 19
  38206. ];
  38207. var indices = new Array();
  38208. var positions = new Array();
  38209. var normals = new Array();
  38210. var uvs = new Array();
  38211. var current_indice = 0;
  38212. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38213. var face_vertex_pos = new Array(3);
  38214. var face_vertex_uv = new Array(3);
  38215. var v012;
  38216. for (v012 = 0; v012 < 3; v012++) {
  38217. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38218. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38219. }
  38220. // create all with normals
  38221. for (var face = 0; face < 20; face++) {
  38222. // 3 vertex per face
  38223. for (v012 = 0; v012 < 3; v012++) {
  38224. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38225. var v_id = ico_indices[3 * face + v012];
  38226. // vertex have 3D position (x,y,z)
  38227. 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]);
  38228. // Normalize to get normal, then scale to radius
  38229. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38230. // uv Coordinates from vertex ID
  38231. 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);
  38232. }
  38233. // Subdivide the face (interpolate pos, norm, uv)
  38234. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38235. // - norm is linear interpolation of vertex corner normal
  38236. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38237. // - uv is linear interpolation
  38238. //
  38239. // Topology is as below for sub-divide by 2
  38240. // vertex shown as v0,v1,v2
  38241. // interp index is i1 to progress in range [v0,v1[
  38242. // interp index is i2 to progress in range [v0,v2[
  38243. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38244. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38245. //
  38246. //
  38247. // i2 v2
  38248. // ^ ^
  38249. // / / \
  38250. // / / \
  38251. // / / \
  38252. // / / (0,1) \
  38253. // / #---------\
  38254. // / / \ (0,0)'/ \
  38255. // / / \ / \
  38256. // / / \ / \
  38257. // / / (0,0) \ / (1,0) \
  38258. // / #---------#---------\
  38259. // v0 v1
  38260. //
  38261. // --------------------> i1
  38262. //
  38263. // interp of (i1,i2):
  38264. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38265. // along i1 : lerp(x0,x1, i1/(S-i2))
  38266. //
  38267. // centroid of triangle is needed to get help normal computation
  38268. // (c1,c2) are used for centroid location
  38269. var interp_vertex = function (i1, i2, c1, c2) {
  38270. // vertex is interpolated from
  38271. // - face_vertex_pos[0..2]
  38272. // - face_vertex_uv[0..2]
  38273. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38274. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38275. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38276. pos_interp.normalize();
  38277. var vertex_normal;
  38278. if (flat) {
  38279. // in flat mode, recalculate normal as face centroid normal
  38280. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38281. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38282. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38283. }
  38284. else {
  38285. // in smooth mode, recalculate normal from each single vertex position
  38286. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38287. }
  38288. // Vertex normal need correction due to X,Y,Z radius scaling
  38289. vertex_normal.x /= radiusX;
  38290. vertex_normal.y /= radiusY;
  38291. vertex_normal.z /= radiusZ;
  38292. vertex_normal.normalize();
  38293. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38294. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38295. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38296. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38297. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38298. uvs.push(uv_interp.x, uv_interp.y);
  38299. // push each vertex has member of a face
  38300. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38301. indices.push(current_indice);
  38302. current_indice++;
  38303. };
  38304. for (var i2 = 0; i2 < subdivisions; i2++) {
  38305. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38306. // face : (i1,i2) for /\ :
  38307. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38308. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38309. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38310. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38311. if (i1 + i2 + 1 < subdivisions) {
  38312. // face : (i1,i2)' for \/ :
  38313. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38314. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38315. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38316. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38317. }
  38318. }
  38319. }
  38320. }
  38321. // Sides
  38322. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38323. // Result
  38324. var vertexData = new VertexData();
  38325. vertexData.indices = indices;
  38326. vertexData.positions = positions;
  38327. vertexData.normals = normals;
  38328. vertexData.uvs = uvs;
  38329. return vertexData;
  38330. };
  38331. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38332. /**
  38333. * Creates the VertexData for a Polyhedron
  38334. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38335. * * type provided types are:
  38336. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38337. * * 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)
  38338. * * size the size of the IcoSphere, optional default 1
  38339. * * sizeX allows stretching in the x direction, optional, default size
  38340. * * sizeY allows stretching in the y direction, optional, default size
  38341. * * sizeZ allows stretching in the z direction, optional, default size
  38342. * * 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
  38343. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38344. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38345. * * flat when true creates a flat shaded mesh, optional, default true
  38346. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38347. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38348. * * 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)
  38349. * * 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)
  38350. * @returns the VertexData of the Polyhedron
  38351. */
  38352. VertexData.CreatePolyhedron = function (options) {
  38353. // provided polyhedron types :
  38354. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38355. // 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)
  38356. var polyhedra = [];
  38357. 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]] };
  38358. 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]] };
  38359. polyhedra[2] = {
  38360. 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]],
  38361. 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]]
  38362. };
  38363. polyhedra[3] = {
  38364. 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]],
  38365. 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]]
  38366. };
  38367. polyhedra[4] = {
  38368. 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]],
  38369. 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]]
  38370. };
  38371. 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]] };
  38372. 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]] };
  38373. 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]] };
  38374. 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]] };
  38375. 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]] };
  38376. 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]] };
  38377. 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]] };
  38378. 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]] };
  38379. 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]] };
  38380. polyhedra[14] = {
  38381. 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]],
  38382. 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]]
  38383. };
  38384. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38385. var size = options.size;
  38386. var sizeX = options.sizeX || size || 1;
  38387. var sizeY = options.sizeY || size || 1;
  38388. var sizeZ = options.sizeZ || size || 1;
  38389. var data = options.custom || polyhedra[type];
  38390. var nbfaces = data.face.length;
  38391. var faceUV = options.faceUV || new Array(nbfaces);
  38392. var faceColors = options.faceColors;
  38393. var flat = (options.flat === undefined) ? true : options.flat;
  38394. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38395. var positions = new Array();
  38396. var indices = new Array();
  38397. var normals = new Array();
  38398. var uvs = new Array();
  38399. var colors = new Array();
  38400. var index = 0;
  38401. var faceIdx = 0; // face cursor in the array "indexes"
  38402. var indexes = new Array();
  38403. var i = 0;
  38404. var f = 0;
  38405. var u, v, ang, x, y, tmp;
  38406. // default face colors and UV if undefined
  38407. if (flat) {
  38408. for (f = 0; f < nbfaces; f++) {
  38409. if (faceColors && faceColors[f] === undefined) {
  38410. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38411. }
  38412. if (faceUV && faceUV[f] === undefined) {
  38413. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38414. }
  38415. }
  38416. }
  38417. if (!flat) {
  38418. for (i = 0; i < data.vertex.length; i++) {
  38419. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38420. uvs.push(0, 0);
  38421. }
  38422. for (f = 0; f < nbfaces; f++) {
  38423. for (i = 0; i < data.face[f].length - 2; i++) {
  38424. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38425. }
  38426. }
  38427. }
  38428. else {
  38429. for (f = 0; f < nbfaces; f++) {
  38430. var fl = data.face[f].length; // number of vertices of the current face
  38431. ang = 2 * Math.PI / fl;
  38432. x = 0.5 * Math.tan(ang / 2);
  38433. y = 0.5;
  38434. // positions, uvs, colors
  38435. for (i = 0; i < fl; i++) {
  38436. // positions
  38437. 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);
  38438. indexes.push(index);
  38439. index++;
  38440. // uvs
  38441. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38442. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38443. uvs.push(u, v);
  38444. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38445. y = x * Math.sin(ang) + y * Math.cos(ang);
  38446. x = tmp;
  38447. // colors
  38448. if (faceColors) {
  38449. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38450. }
  38451. }
  38452. // indices from indexes
  38453. for (i = 0; i < fl - 2; i++) {
  38454. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38455. }
  38456. faceIdx += fl;
  38457. }
  38458. }
  38459. VertexData.ComputeNormals(positions, indices, normals);
  38460. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38461. var vertexData = new VertexData();
  38462. vertexData.positions = positions;
  38463. vertexData.indices = indices;
  38464. vertexData.normals = normals;
  38465. vertexData.uvs = uvs;
  38466. if (faceColors && flat) {
  38467. vertexData.colors = colors;
  38468. }
  38469. return vertexData;
  38470. };
  38471. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38472. /**
  38473. * Creates the VertexData for a TorusKnot
  38474. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38475. * * radius the radius of the torus knot, optional, default 2
  38476. * * tube the thickness of the tube, optional, default 0.5
  38477. * * radialSegments the number of sides on each tube segments, optional, default 32
  38478. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38479. * * p the number of windings around the z axis, optional, default 2
  38480. * * q the number of windings around the x axis, optional, default 3
  38481. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38482. * * 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)
  38483. * * 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)
  38484. * @returns the VertexData of the Torus Knot
  38485. */
  38486. VertexData.CreateTorusKnot = function (options) {
  38487. var indices = new Array();
  38488. var positions = new Array();
  38489. var normals = new Array();
  38490. var uvs = new Array();
  38491. var radius = options.radius || 2;
  38492. var tube = options.tube || 0.5;
  38493. var radialSegments = options.radialSegments || 32;
  38494. var tubularSegments = options.tubularSegments || 32;
  38495. var p = options.p || 2;
  38496. var q = options.q || 3;
  38497. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38498. // Helper
  38499. var getPos = function (angle) {
  38500. var cu = Math.cos(angle);
  38501. var su = Math.sin(angle);
  38502. var quOverP = q / p * angle;
  38503. var cs = Math.cos(quOverP);
  38504. var tx = radius * (2 + cs) * 0.5 * cu;
  38505. var ty = radius * (2 + cs) * su * 0.5;
  38506. var tz = radius * Math.sin(quOverP) * 0.5;
  38507. return new BABYLON.Vector3(tx, ty, tz);
  38508. };
  38509. // Vertices
  38510. var i;
  38511. var j;
  38512. for (i = 0; i <= radialSegments; i++) {
  38513. var modI = i % radialSegments;
  38514. var u = modI / radialSegments * 2 * p * Math.PI;
  38515. var p1 = getPos(u);
  38516. var p2 = getPos(u + 0.01);
  38517. var tang = p2.subtract(p1);
  38518. var n = p2.add(p1);
  38519. var bitan = BABYLON.Vector3.Cross(tang, n);
  38520. n = BABYLON.Vector3.Cross(bitan, tang);
  38521. bitan.normalize();
  38522. n.normalize();
  38523. for (j = 0; j < tubularSegments; j++) {
  38524. var modJ = j % tubularSegments;
  38525. var v = modJ / tubularSegments * 2 * Math.PI;
  38526. var cx = -tube * Math.cos(v);
  38527. var cy = tube * Math.sin(v);
  38528. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38529. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38530. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38531. uvs.push(i / radialSegments);
  38532. uvs.push(j / tubularSegments);
  38533. }
  38534. }
  38535. for (i = 0; i < radialSegments; i++) {
  38536. for (j = 0; j < tubularSegments; j++) {
  38537. var jNext = (j + 1) % tubularSegments;
  38538. var a = i * tubularSegments + j;
  38539. var b = (i + 1) * tubularSegments + j;
  38540. var c = (i + 1) * tubularSegments + jNext;
  38541. var d = i * tubularSegments + jNext;
  38542. indices.push(d);
  38543. indices.push(b);
  38544. indices.push(a);
  38545. indices.push(d);
  38546. indices.push(c);
  38547. indices.push(b);
  38548. }
  38549. }
  38550. // Normals
  38551. VertexData.ComputeNormals(positions, indices, normals);
  38552. // Sides
  38553. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38554. // Result
  38555. var vertexData = new VertexData();
  38556. vertexData.indices = indices;
  38557. vertexData.positions = positions;
  38558. vertexData.normals = normals;
  38559. vertexData.uvs = uvs;
  38560. return vertexData;
  38561. };
  38562. // Tools
  38563. /**
  38564. * Compute normals for given positions and indices
  38565. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38566. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38567. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38568. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38569. * * facetNormals : optional array of facet normals (vector3)
  38570. * * facetPositions : optional array of facet positions (vector3)
  38571. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38572. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38573. * * bInfo : optional bounding info, required for facetPartitioning computation
  38574. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38575. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38576. * * useRightHandedSystem: optional boolean to for right handed system computation
  38577. * * depthSort : optional boolean to enable the facet depth sort computation
  38578. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38579. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38580. */
  38581. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38582. // temporary scalar variables
  38583. var index = 0; // facet index
  38584. var p1p2x = 0.0; // p1p2 vector x coordinate
  38585. var p1p2y = 0.0; // p1p2 vector y coordinate
  38586. var p1p2z = 0.0; // p1p2 vector z coordinate
  38587. var p3p2x = 0.0; // p3p2 vector x coordinate
  38588. var p3p2y = 0.0; // p3p2 vector y coordinate
  38589. var p3p2z = 0.0; // p3p2 vector z coordinate
  38590. var faceNormalx = 0.0; // facet normal x coordinate
  38591. var faceNormaly = 0.0; // facet normal y coordinate
  38592. var faceNormalz = 0.0; // facet normal z coordinate
  38593. var length = 0.0; // facet normal length before normalization
  38594. var v1x = 0; // vector1 x index in the positions array
  38595. var v1y = 0; // vector1 y index in the positions array
  38596. var v1z = 0; // vector1 z index in the positions array
  38597. var v2x = 0; // vector2 x index in the positions array
  38598. var v2y = 0; // vector2 y index in the positions array
  38599. var v2z = 0; // vector2 z index in the positions array
  38600. var v3x = 0; // vector3 x index in the positions array
  38601. var v3y = 0; // vector3 y index in the positions array
  38602. var v3z = 0; // vector3 z index in the positions array
  38603. var computeFacetNormals = false;
  38604. var computeFacetPositions = false;
  38605. var computeFacetPartitioning = false;
  38606. var computeDepthSort = false;
  38607. var faceNormalSign = 1;
  38608. var ratio = 0;
  38609. var distanceTo = null;
  38610. if (options) {
  38611. computeFacetNormals = (options.facetNormals) ? true : false;
  38612. computeFacetPositions = (options.facetPositions) ? true : false;
  38613. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38614. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38615. ratio = options.ratio || 0;
  38616. computeDepthSort = (options.depthSort) ? true : false;
  38617. distanceTo = (options.distanceTo);
  38618. if (computeDepthSort) {
  38619. if (distanceTo === undefined) {
  38620. distanceTo = BABYLON.Vector3.Zero();
  38621. }
  38622. var depthSortedFacets = options.depthSortedFacets;
  38623. }
  38624. }
  38625. // facetPartitioning reinit if needed
  38626. var xSubRatio = 0;
  38627. var ySubRatio = 0;
  38628. var zSubRatio = 0;
  38629. var subSq = 0;
  38630. if (computeFacetPartitioning && options && options.bbSize) {
  38631. var ox = 0; // X partitioning index for facet position
  38632. var oy = 0; // Y partinioning index for facet position
  38633. var oz = 0; // Z partinioning index for facet position
  38634. var b1x = 0; // X partitioning index for facet v1 vertex
  38635. var b1y = 0; // Y partitioning index for facet v1 vertex
  38636. var b1z = 0; // z partitioning index for facet v1 vertex
  38637. var b2x = 0; // X partitioning index for facet v2 vertex
  38638. var b2y = 0; // Y partitioning index for facet v2 vertex
  38639. var b2z = 0; // Z partitioning index for facet v2 vertex
  38640. var b3x = 0; // X partitioning index for facet v3 vertex
  38641. var b3y = 0; // Y partitioning index for facet v3 vertex
  38642. var b3z = 0; // Z partitioning index for facet v3 vertex
  38643. var block_idx_o = 0; // facet barycenter block index
  38644. var block_idx_v1 = 0; // v1 vertex block index
  38645. var block_idx_v2 = 0; // v2 vertex block index
  38646. var block_idx_v3 = 0; // v3 vertex block index
  38647. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38648. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38649. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38650. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38651. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38652. subSq = options.subDiv.max * options.subDiv.max;
  38653. options.facetPartitioning.length = 0;
  38654. }
  38655. // reset the normals
  38656. for (index = 0; index < positions.length; index++) {
  38657. normals[index] = 0.0;
  38658. }
  38659. // Loop : 1 indice triplet = 1 facet
  38660. var nbFaces = (indices.length / 3) | 0;
  38661. for (index = 0; index < nbFaces; index++) {
  38662. // get the indexes of the coordinates of each vertex of the facet
  38663. v1x = indices[index * 3] * 3;
  38664. v1y = v1x + 1;
  38665. v1z = v1x + 2;
  38666. v2x = indices[index * 3 + 1] * 3;
  38667. v2y = v2x + 1;
  38668. v2z = v2x + 2;
  38669. v3x = indices[index * 3 + 2] * 3;
  38670. v3y = v3x + 1;
  38671. v3z = v3x + 2;
  38672. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38673. p1p2y = positions[v1y] - positions[v2y];
  38674. p1p2z = positions[v1z] - positions[v2z];
  38675. p3p2x = positions[v3x] - positions[v2x];
  38676. p3p2y = positions[v3y] - positions[v2y];
  38677. p3p2z = positions[v3z] - positions[v2z];
  38678. // compute the face normal with the cross product
  38679. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38680. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38681. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38682. // normalize this normal and store it in the array facetData
  38683. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38684. length = (length === 0) ? 1.0 : length;
  38685. faceNormalx /= length;
  38686. faceNormaly /= length;
  38687. faceNormalz /= length;
  38688. if (computeFacetNormals && options) {
  38689. options.facetNormals[index].x = faceNormalx;
  38690. options.facetNormals[index].y = faceNormaly;
  38691. options.facetNormals[index].z = faceNormalz;
  38692. }
  38693. if (computeFacetPositions && options) {
  38694. // compute and the facet barycenter coordinates in the array facetPositions
  38695. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38696. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38697. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38698. }
  38699. if (computeFacetPartitioning && options) {
  38700. // store the facet indexes in arrays in the main facetPartitioning array :
  38701. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38702. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38703. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38704. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38705. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38706. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38707. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38708. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38709. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38710. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38711. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38712. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38713. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38714. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38715. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38716. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38717. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38718. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38719. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38720. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38721. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38722. // push each facet index in each block containing the vertex
  38723. options.facetPartitioning[block_idx_v1].push(index);
  38724. if (block_idx_v2 != block_idx_v1) {
  38725. options.facetPartitioning[block_idx_v2].push(index);
  38726. }
  38727. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38728. options.facetPartitioning[block_idx_v3].push(index);
  38729. }
  38730. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38731. options.facetPartitioning[block_idx_o].push(index);
  38732. }
  38733. }
  38734. if (computeDepthSort && options && options.facetPositions) {
  38735. var dsf = depthSortedFacets[index];
  38736. dsf.ind = index * 3;
  38737. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38738. }
  38739. // compute the normals anyway
  38740. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38741. normals[v1y] += faceNormaly;
  38742. normals[v1z] += faceNormalz;
  38743. normals[v2x] += faceNormalx;
  38744. normals[v2y] += faceNormaly;
  38745. normals[v2z] += faceNormalz;
  38746. normals[v3x] += faceNormalx;
  38747. normals[v3y] += faceNormaly;
  38748. normals[v3z] += faceNormalz;
  38749. }
  38750. // last normalization of each normal
  38751. for (index = 0; index < normals.length / 3; index++) {
  38752. faceNormalx = normals[index * 3];
  38753. faceNormaly = normals[index * 3 + 1];
  38754. faceNormalz = normals[index * 3 + 2];
  38755. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38756. length = (length === 0) ? 1.0 : length;
  38757. faceNormalx /= length;
  38758. faceNormaly /= length;
  38759. faceNormalz /= length;
  38760. normals[index * 3] = faceNormalx;
  38761. normals[index * 3 + 1] = faceNormaly;
  38762. normals[index * 3 + 2] = faceNormalz;
  38763. }
  38764. };
  38765. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38766. var li = indices.length;
  38767. var ln = normals.length;
  38768. var i;
  38769. var n;
  38770. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38771. switch (sideOrientation) {
  38772. case BABYLON.Mesh.FRONTSIDE:
  38773. // nothing changed
  38774. break;
  38775. case BABYLON.Mesh.BACKSIDE:
  38776. var tmp;
  38777. // indices
  38778. for (i = 0; i < li; i += 3) {
  38779. tmp = indices[i];
  38780. indices[i] = indices[i + 2];
  38781. indices[i + 2] = tmp;
  38782. }
  38783. // normals
  38784. for (n = 0; n < ln; n++) {
  38785. normals[n] = -normals[n];
  38786. }
  38787. break;
  38788. case BABYLON.Mesh.DOUBLESIDE:
  38789. // positions
  38790. var lp = positions.length;
  38791. var l = lp / 3;
  38792. for (var p = 0; p < lp; p++) {
  38793. positions[lp + p] = positions[p];
  38794. }
  38795. // indices
  38796. for (i = 0; i < li; i += 3) {
  38797. indices[i + li] = indices[i + 2] + l;
  38798. indices[i + 1 + li] = indices[i + 1] + l;
  38799. indices[i + 2 + li] = indices[i] + l;
  38800. }
  38801. // normals
  38802. for (n = 0; n < ln; n++) {
  38803. normals[ln + n] = -normals[n];
  38804. }
  38805. // uvs
  38806. var lu = uvs.length;
  38807. var u = 0;
  38808. for (u = 0; u < lu; u++) {
  38809. uvs[u + lu] = uvs[u];
  38810. }
  38811. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38812. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38813. u = 0;
  38814. for (i = 0; i < lu / 2; i++) {
  38815. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38816. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38817. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38818. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38819. u += 2;
  38820. }
  38821. break;
  38822. }
  38823. };
  38824. /**
  38825. * Applies VertexData created from the imported parameters to the geometry
  38826. * @param parsedVertexData the parsed data from an imported file
  38827. * @param geometry the geometry to apply the VertexData to
  38828. */
  38829. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38830. var vertexData = new VertexData();
  38831. // positions
  38832. var positions = parsedVertexData.positions;
  38833. if (positions) {
  38834. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38835. }
  38836. // normals
  38837. var normals = parsedVertexData.normals;
  38838. if (normals) {
  38839. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38840. }
  38841. // tangents
  38842. var tangents = parsedVertexData.tangents;
  38843. if (tangents) {
  38844. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38845. }
  38846. // uvs
  38847. var uvs = parsedVertexData.uvs;
  38848. if (uvs) {
  38849. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38850. }
  38851. // uv2s
  38852. var uv2s = parsedVertexData.uv2s;
  38853. if (uv2s) {
  38854. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38855. }
  38856. // uv3s
  38857. var uv3s = parsedVertexData.uv3s;
  38858. if (uv3s) {
  38859. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38860. }
  38861. // uv4s
  38862. var uv4s = parsedVertexData.uv4s;
  38863. if (uv4s) {
  38864. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38865. }
  38866. // uv5s
  38867. var uv5s = parsedVertexData.uv5s;
  38868. if (uv5s) {
  38869. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38870. }
  38871. // uv6s
  38872. var uv6s = parsedVertexData.uv6s;
  38873. if (uv6s) {
  38874. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38875. }
  38876. // colors
  38877. var colors = parsedVertexData.colors;
  38878. if (colors) {
  38879. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38880. }
  38881. // matricesIndices
  38882. var matricesIndices = parsedVertexData.matricesIndices;
  38883. if (matricesIndices) {
  38884. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38885. }
  38886. // matricesWeights
  38887. var matricesWeights = parsedVertexData.matricesWeights;
  38888. if (matricesWeights) {
  38889. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38890. }
  38891. // indices
  38892. var indices = parsedVertexData.indices;
  38893. if (indices) {
  38894. vertexData.indices = indices;
  38895. }
  38896. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38897. };
  38898. return VertexData;
  38899. }());
  38900. BABYLON.VertexData = VertexData;
  38901. })(BABYLON || (BABYLON = {}));
  38902. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38903. var BABYLON;
  38904. (function (BABYLON) {
  38905. /**
  38906. * Class used to store geometry data (vertex buffers + index buffer)
  38907. */
  38908. var Geometry = /** @class */ (function () {
  38909. /**
  38910. * Creates a new geometry
  38911. * @param id defines the unique ID
  38912. * @param scene defines the hosting scene
  38913. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38914. * @param updatable defines if geometry must be updatable (false by default)
  38915. * @param mesh defines the mesh that will be associated with the geometry
  38916. */
  38917. function Geometry(id, scene, vertexData, updatable, mesh) {
  38918. if (updatable === void 0) { updatable = false; }
  38919. if (mesh === void 0) { mesh = null; }
  38920. /**
  38921. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38922. */
  38923. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38924. this._totalVertices = 0;
  38925. this._isDisposed = false;
  38926. this._indexBufferIsUpdatable = false;
  38927. this.id = id;
  38928. this._engine = scene.getEngine();
  38929. this._meshes = [];
  38930. this._scene = scene;
  38931. //Init vertex buffer cache
  38932. this._vertexBuffers = {};
  38933. this._indices = [];
  38934. this._updatable = updatable;
  38935. // vertexData
  38936. if (vertexData) {
  38937. this.setAllVerticesData(vertexData, updatable);
  38938. }
  38939. else {
  38940. this._totalVertices = 0;
  38941. this._indices = [];
  38942. }
  38943. if (this._engine.getCaps().vertexArrayObject) {
  38944. this._vertexArrayObjects = {};
  38945. }
  38946. // applyToMesh
  38947. if (mesh) {
  38948. if (mesh.getClassName() === "LinesMesh") {
  38949. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38950. this._updateExtend();
  38951. }
  38952. this.applyToMesh(mesh);
  38953. mesh.computeWorldMatrix(true);
  38954. }
  38955. }
  38956. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38957. /**
  38958. * 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
  38959. */
  38960. get: function () {
  38961. return this._boundingBias;
  38962. },
  38963. /**
  38964. * 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
  38965. */
  38966. set: function (value) {
  38967. if (this._boundingBias && this._boundingBias.equals(value)) {
  38968. return;
  38969. }
  38970. this._boundingBias = value.clone();
  38971. this._updateBoundingInfo(true, null);
  38972. },
  38973. enumerable: true,
  38974. configurable: true
  38975. });
  38976. /**
  38977. * Static function used to attach a new empty geometry to a mesh
  38978. * @param mesh defines the mesh to attach the geometry to
  38979. * @returns the new {BABYLON.Geometry}
  38980. */
  38981. Geometry.CreateGeometryForMesh = function (mesh) {
  38982. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38983. geometry.applyToMesh(mesh);
  38984. return geometry;
  38985. };
  38986. Object.defineProperty(Geometry.prototype, "extend", {
  38987. /**
  38988. * Gets the current extend of the geometry
  38989. */
  38990. get: function () {
  38991. return this._extend;
  38992. },
  38993. enumerable: true,
  38994. configurable: true
  38995. });
  38996. /**
  38997. * Gets the hosting scene
  38998. * @returns the hosting {BABYLON.Scene}
  38999. */
  39000. Geometry.prototype.getScene = function () {
  39001. return this._scene;
  39002. };
  39003. /**
  39004. * Gets the hosting engine
  39005. * @returns the hosting {BABYLON.Engine}
  39006. */
  39007. Geometry.prototype.getEngine = function () {
  39008. return this._engine;
  39009. };
  39010. /**
  39011. * Defines if the geometry is ready to use
  39012. * @returns true if the geometry is ready to be used
  39013. */
  39014. Geometry.prototype.isReady = function () {
  39015. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39016. };
  39017. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39018. /**
  39019. * Gets a value indicating that the geometry should not be serialized
  39020. */
  39021. get: function () {
  39022. for (var index = 0; index < this._meshes.length; index++) {
  39023. if (!this._meshes[index].doNotSerialize) {
  39024. return false;
  39025. }
  39026. }
  39027. return true;
  39028. },
  39029. enumerable: true,
  39030. configurable: true
  39031. });
  39032. /** @hidden */
  39033. Geometry.prototype._rebuild = function () {
  39034. if (this._vertexArrayObjects) {
  39035. this._vertexArrayObjects = {};
  39036. }
  39037. // Index buffer
  39038. if (this._meshes.length !== 0 && this._indices) {
  39039. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39040. }
  39041. // Vertex buffers
  39042. for (var key in this._vertexBuffers) {
  39043. var vertexBuffer = this._vertexBuffers[key];
  39044. vertexBuffer._rebuild();
  39045. }
  39046. };
  39047. /**
  39048. * Affects all gemetry data in one call
  39049. * @param vertexData defines the geometry data
  39050. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39051. */
  39052. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39053. vertexData.applyToGeometry(this, updatable);
  39054. this.notifyUpdate();
  39055. };
  39056. /**
  39057. * Set specific vertex data
  39058. * @param kind defines the data kind (Position, normal, etc...)
  39059. * @param data defines the vertex data to use
  39060. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39061. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39062. */
  39063. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39064. if (updatable === void 0) { updatable = false; }
  39065. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39066. this.setVerticesBuffer(buffer);
  39067. };
  39068. /**
  39069. * Removes a specific vertex data
  39070. * @param kind defines the data kind (Position, normal, etc...)
  39071. */
  39072. Geometry.prototype.removeVerticesData = function (kind) {
  39073. if (this._vertexBuffers[kind]) {
  39074. this._vertexBuffers[kind].dispose();
  39075. delete this._vertexBuffers[kind];
  39076. }
  39077. };
  39078. /**
  39079. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39080. * @param buffer defines the vertex buffer to use
  39081. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39082. */
  39083. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39084. if (totalVertices === void 0) { totalVertices = null; }
  39085. var kind = buffer.getKind();
  39086. if (this._vertexBuffers[kind]) {
  39087. this._vertexBuffers[kind].dispose();
  39088. }
  39089. this._vertexBuffers[kind] = buffer;
  39090. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39091. var data = buffer.getData();
  39092. if (totalVertices != null) {
  39093. this._totalVertices = totalVertices;
  39094. }
  39095. else {
  39096. if (data != null) {
  39097. this._totalVertices = data.length / (buffer.byteStride / 4);
  39098. }
  39099. }
  39100. this._updateExtend(data);
  39101. this._resetPointsArrayCache();
  39102. var meshes = this._meshes;
  39103. var numOfMeshes = meshes.length;
  39104. for (var index = 0; index < numOfMeshes; index++) {
  39105. var mesh = meshes[index];
  39106. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39107. mesh._createGlobalSubMesh(false);
  39108. mesh.computeWorldMatrix(true);
  39109. }
  39110. }
  39111. this.notifyUpdate(kind);
  39112. if (this._vertexArrayObjects) {
  39113. this._disposeVertexArrayObjects();
  39114. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39115. }
  39116. };
  39117. /**
  39118. * Update a specific vertex buffer
  39119. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39120. * It will do nothing if the buffer is not updatable
  39121. * @param kind defines the data kind (Position, normal, etc...)
  39122. * @param data defines the data to use
  39123. * @param offset defines the offset in the target buffer where to store the data
  39124. * @param useBytes set to true if the offset is in bytes
  39125. */
  39126. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39127. if (useBytes === void 0) { useBytes = false; }
  39128. var vertexBuffer = this.getVertexBuffer(kind);
  39129. if (!vertexBuffer) {
  39130. return;
  39131. }
  39132. vertexBuffer.updateDirectly(data, offset, useBytes);
  39133. this.notifyUpdate(kind);
  39134. };
  39135. /**
  39136. * Update a specific vertex buffer
  39137. * This function will create a new buffer if the current one is not updatable
  39138. * @param kind defines the data kind (Position, normal, etc...)
  39139. * @param data defines the data to use
  39140. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39141. */
  39142. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39143. if (updateExtends === void 0) { updateExtends = false; }
  39144. var vertexBuffer = this.getVertexBuffer(kind);
  39145. if (!vertexBuffer) {
  39146. return;
  39147. }
  39148. vertexBuffer.update(data);
  39149. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39150. this._updateBoundingInfo(updateExtends, data);
  39151. }
  39152. this.notifyUpdate(kind);
  39153. };
  39154. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39155. if (updateExtends) {
  39156. this._updateExtend(data);
  39157. }
  39158. var meshes = this._meshes;
  39159. var numOfMeshes = meshes.length;
  39160. this._resetPointsArrayCache();
  39161. for (var index = 0; index < numOfMeshes; index++) {
  39162. var mesh = meshes[index];
  39163. if (updateExtends) {
  39164. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39165. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39166. var subMesh = mesh.subMeshes[subIndex];
  39167. subMesh.refreshBoundingInfo();
  39168. }
  39169. }
  39170. }
  39171. };
  39172. /** @hidden */
  39173. Geometry.prototype._bind = function (effect, indexToBind) {
  39174. if (!effect) {
  39175. return;
  39176. }
  39177. if (indexToBind === undefined) {
  39178. indexToBind = this._indexBuffer;
  39179. }
  39180. var vbs = this.getVertexBuffers();
  39181. if (!vbs) {
  39182. return;
  39183. }
  39184. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39185. this._engine.bindBuffers(vbs, indexToBind, effect);
  39186. return;
  39187. }
  39188. // Using VAO
  39189. if (!this._vertexArrayObjects[effect.key]) {
  39190. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39191. }
  39192. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39193. };
  39194. /**
  39195. * Gets total number of vertices
  39196. * @returns the total number of vertices
  39197. */
  39198. Geometry.prototype.getTotalVertices = function () {
  39199. if (!this.isReady()) {
  39200. return 0;
  39201. }
  39202. return this._totalVertices;
  39203. };
  39204. /**
  39205. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39206. * @param kind defines the data kind (Position, normal, etc...)
  39207. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39208. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39209. * @returns a float array containing vertex data
  39210. */
  39211. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39212. var vertexBuffer = this.getVertexBuffer(kind);
  39213. if (!vertexBuffer) {
  39214. return null;
  39215. }
  39216. var data = vertexBuffer.getData();
  39217. if (!data) {
  39218. return null;
  39219. }
  39220. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39221. var count = this._totalVertices * vertexBuffer.getSize();
  39222. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39223. var copy_1 = new Array(count);
  39224. vertexBuffer.forEach(count, function (value, index) {
  39225. copy_1[index] = value;
  39226. });
  39227. return copy_1;
  39228. }
  39229. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39230. if (data instanceof Array) {
  39231. var offset = vertexBuffer.byteOffset / 4;
  39232. return BABYLON.Tools.Slice(data, offset, offset + count);
  39233. }
  39234. else if (data instanceof ArrayBuffer) {
  39235. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39236. }
  39237. else {
  39238. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39239. }
  39240. }
  39241. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39242. return BABYLON.Tools.Slice(data);
  39243. }
  39244. return data;
  39245. };
  39246. /**
  39247. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39248. * @param kind defines the data kind (Position, normal, etc...)
  39249. * @returns true if the vertex buffer with the specified kind is updatable
  39250. */
  39251. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39252. var vb = this._vertexBuffers[kind];
  39253. if (!vb) {
  39254. return false;
  39255. }
  39256. return vb.isUpdatable();
  39257. };
  39258. /**
  39259. * Gets a specific vertex buffer
  39260. * @param kind defines the data kind (Position, normal, etc...)
  39261. * @returns a {BABYLON.VertexBuffer}
  39262. */
  39263. Geometry.prototype.getVertexBuffer = function (kind) {
  39264. if (!this.isReady()) {
  39265. return null;
  39266. }
  39267. return this._vertexBuffers[kind];
  39268. };
  39269. /**
  39270. * Returns all vertex buffers
  39271. * @return an object holding all vertex buffers indexed by kind
  39272. */
  39273. Geometry.prototype.getVertexBuffers = function () {
  39274. if (!this.isReady()) {
  39275. return null;
  39276. }
  39277. return this._vertexBuffers;
  39278. };
  39279. /**
  39280. * Gets a boolean indicating if specific vertex buffer is present
  39281. * @param kind defines the data kind (Position, normal, etc...)
  39282. * @returns true if data is present
  39283. */
  39284. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39285. if (!this._vertexBuffers) {
  39286. if (this._delayInfo) {
  39287. return this._delayInfo.indexOf(kind) !== -1;
  39288. }
  39289. return false;
  39290. }
  39291. return this._vertexBuffers[kind] !== undefined;
  39292. };
  39293. /**
  39294. * Gets a list of all attached data kinds (Position, normal, etc...)
  39295. * @returns a list of string containing all kinds
  39296. */
  39297. Geometry.prototype.getVerticesDataKinds = function () {
  39298. var result = [];
  39299. var kind;
  39300. if (!this._vertexBuffers && this._delayInfo) {
  39301. for (kind in this._delayInfo) {
  39302. result.push(kind);
  39303. }
  39304. }
  39305. else {
  39306. for (kind in this._vertexBuffers) {
  39307. result.push(kind);
  39308. }
  39309. }
  39310. return result;
  39311. };
  39312. /**
  39313. * Update index buffer
  39314. * @param indices defines the indices to store in the index buffer
  39315. * @param offset defines the offset in the target buffer where to store the data
  39316. */
  39317. Geometry.prototype.updateIndices = function (indices, offset) {
  39318. if (!this._indexBuffer) {
  39319. return;
  39320. }
  39321. if (!this._indexBufferIsUpdatable) {
  39322. this.setIndices(indices, null, true);
  39323. }
  39324. else {
  39325. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39326. }
  39327. };
  39328. /**
  39329. * Creates a new index buffer
  39330. * @param indices defines the indices to store in the index buffer
  39331. * @param totalVertices defines the total number of vertices (could be null)
  39332. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39333. */
  39334. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39335. if (totalVertices === void 0) { totalVertices = null; }
  39336. if (updatable === void 0) { updatable = false; }
  39337. if (this._indexBuffer) {
  39338. this._engine._releaseBuffer(this._indexBuffer);
  39339. }
  39340. this._disposeVertexArrayObjects();
  39341. this._indices = indices;
  39342. this._indexBufferIsUpdatable = updatable;
  39343. if (this._meshes.length !== 0 && this._indices) {
  39344. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39345. }
  39346. if (totalVertices != undefined) { // including null and undefined
  39347. this._totalVertices = totalVertices;
  39348. }
  39349. var meshes = this._meshes;
  39350. var numOfMeshes = meshes.length;
  39351. for (var index = 0; index < numOfMeshes; index++) {
  39352. meshes[index]._createGlobalSubMesh(true);
  39353. }
  39354. this.notifyUpdate();
  39355. };
  39356. /**
  39357. * Return the total number of indices
  39358. * @returns the total number of indices
  39359. */
  39360. Geometry.prototype.getTotalIndices = function () {
  39361. if (!this.isReady()) {
  39362. return 0;
  39363. }
  39364. return this._indices.length;
  39365. };
  39366. /**
  39367. * Gets the index buffer array
  39368. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39369. * @returns the index buffer array
  39370. */
  39371. Geometry.prototype.getIndices = function (copyWhenShared) {
  39372. if (!this.isReady()) {
  39373. return null;
  39374. }
  39375. var orig = this._indices;
  39376. if (!copyWhenShared || this._meshes.length === 1) {
  39377. return orig;
  39378. }
  39379. else {
  39380. var len = orig.length;
  39381. var copy = [];
  39382. for (var i = 0; i < len; i++) {
  39383. copy.push(orig[i]);
  39384. }
  39385. return copy;
  39386. }
  39387. };
  39388. /**
  39389. * Gets the index buffer
  39390. * @return the index buffer
  39391. */
  39392. Geometry.prototype.getIndexBuffer = function () {
  39393. if (!this.isReady()) {
  39394. return null;
  39395. }
  39396. return this._indexBuffer;
  39397. };
  39398. /** @hidden */
  39399. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39400. if (effect === void 0) { effect = null; }
  39401. if (!effect || !this._vertexArrayObjects) {
  39402. return;
  39403. }
  39404. if (this._vertexArrayObjects[effect.key]) {
  39405. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39406. delete this._vertexArrayObjects[effect.key];
  39407. }
  39408. };
  39409. /**
  39410. * Release the associated resources for a specific mesh
  39411. * @param mesh defines the source mesh
  39412. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39413. */
  39414. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39415. var meshes = this._meshes;
  39416. var index = meshes.indexOf(mesh);
  39417. if (index === -1) {
  39418. return;
  39419. }
  39420. meshes.splice(index, 1);
  39421. mesh._geometry = null;
  39422. if (meshes.length === 0 && shouldDispose) {
  39423. this.dispose();
  39424. }
  39425. };
  39426. /**
  39427. * Apply current geometry to a given mesh
  39428. * @param mesh defines the mesh to apply geometry to
  39429. */
  39430. Geometry.prototype.applyToMesh = function (mesh) {
  39431. if (mesh._geometry === this) {
  39432. return;
  39433. }
  39434. var previousGeometry = mesh._geometry;
  39435. if (previousGeometry) {
  39436. previousGeometry.releaseForMesh(mesh);
  39437. }
  39438. var meshes = this._meshes;
  39439. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39440. mesh._geometry = this;
  39441. this._scene.pushGeometry(this);
  39442. meshes.push(mesh);
  39443. if (this.isReady()) {
  39444. this._applyToMesh(mesh);
  39445. }
  39446. else {
  39447. mesh._boundingInfo = this._boundingInfo;
  39448. }
  39449. };
  39450. Geometry.prototype._updateExtend = function (data) {
  39451. if (data === void 0) { data = null; }
  39452. if (!data) {
  39453. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39454. }
  39455. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39456. };
  39457. Geometry.prototype._applyToMesh = function (mesh) {
  39458. var numOfMeshes = this._meshes.length;
  39459. // vertexBuffers
  39460. for (var kind in this._vertexBuffers) {
  39461. if (numOfMeshes === 1) {
  39462. this._vertexBuffers[kind].create();
  39463. }
  39464. var buffer = this._vertexBuffers[kind].getBuffer();
  39465. if (buffer)
  39466. buffer.references = numOfMeshes;
  39467. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39468. if (!this._extend) {
  39469. this._updateExtend();
  39470. }
  39471. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39472. mesh._createGlobalSubMesh(false);
  39473. //bounding info was just created again, world matrix should be applied again.
  39474. mesh._updateBoundingInfo();
  39475. }
  39476. }
  39477. // indexBuffer
  39478. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39479. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39480. }
  39481. if (this._indexBuffer) {
  39482. this._indexBuffer.references = numOfMeshes;
  39483. }
  39484. };
  39485. Geometry.prototype.notifyUpdate = function (kind) {
  39486. if (this.onGeometryUpdated) {
  39487. this.onGeometryUpdated(this, kind);
  39488. }
  39489. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39490. var mesh = _a[_i];
  39491. mesh._markSubMeshesAsAttributesDirty();
  39492. }
  39493. };
  39494. /**
  39495. * Load the geometry if it was flagged as delay loaded
  39496. * @param scene defines the hosting scene
  39497. * @param onLoaded defines a callback called when the geometry is loaded
  39498. */
  39499. Geometry.prototype.load = function (scene, onLoaded) {
  39500. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39501. return;
  39502. }
  39503. if (this.isReady()) {
  39504. if (onLoaded) {
  39505. onLoaded();
  39506. }
  39507. return;
  39508. }
  39509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39510. this._queueLoad(scene, onLoaded);
  39511. };
  39512. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39513. var _this = this;
  39514. if (!this.delayLoadingFile) {
  39515. return;
  39516. }
  39517. scene._addPendingData(this);
  39518. scene._loadFile(this.delayLoadingFile, function (data) {
  39519. if (!_this._delayLoadingFunction) {
  39520. return;
  39521. }
  39522. _this._delayLoadingFunction(JSON.parse(data), _this);
  39523. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39524. _this._delayInfo = [];
  39525. scene._removePendingData(_this);
  39526. var meshes = _this._meshes;
  39527. var numOfMeshes = meshes.length;
  39528. for (var index = 0; index < numOfMeshes; index++) {
  39529. _this._applyToMesh(meshes[index]);
  39530. }
  39531. if (onLoaded) {
  39532. onLoaded();
  39533. }
  39534. }, undefined, true);
  39535. };
  39536. /**
  39537. * Invert the geometry to move from a right handed system to a left handed one.
  39538. */
  39539. Geometry.prototype.toLeftHanded = function () {
  39540. // Flip faces
  39541. var tIndices = this.getIndices(false);
  39542. if (tIndices != null && tIndices.length > 0) {
  39543. for (var i = 0; i < tIndices.length; i += 3) {
  39544. var tTemp = tIndices[i + 0];
  39545. tIndices[i + 0] = tIndices[i + 2];
  39546. tIndices[i + 2] = tTemp;
  39547. }
  39548. this.setIndices(tIndices);
  39549. }
  39550. // Negate position.z
  39551. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39552. if (tPositions != null && tPositions.length > 0) {
  39553. for (var i = 0; i < tPositions.length; i += 3) {
  39554. tPositions[i + 2] = -tPositions[i + 2];
  39555. }
  39556. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39557. }
  39558. // Negate normal.z
  39559. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39560. if (tNormals != null && tNormals.length > 0) {
  39561. for (var i = 0; i < tNormals.length; i += 3) {
  39562. tNormals[i + 2] = -tNormals[i + 2];
  39563. }
  39564. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39565. }
  39566. };
  39567. // Cache
  39568. /** @hidden */
  39569. Geometry.prototype._resetPointsArrayCache = function () {
  39570. this._positions = null;
  39571. };
  39572. /** @hidden */
  39573. Geometry.prototype._generatePointsArray = function () {
  39574. if (this._positions)
  39575. return true;
  39576. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39577. if (!data || data.length === 0) {
  39578. return false;
  39579. }
  39580. this._positions = [];
  39581. for (var index = 0; index < data.length; index += 3) {
  39582. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39583. }
  39584. return true;
  39585. };
  39586. /**
  39587. * Gets a value indicating if the geometry is disposed
  39588. * @returns true if the geometry was disposed
  39589. */
  39590. Geometry.prototype.isDisposed = function () {
  39591. return this._isDisposed;
  39592. };
  39593. Geometry.prototype._disposeVertexArrayObjects = function () {
  39594. if (this._vertexArrayObjects) {
  39595. for (var kind in this._vertexArrayObjects) {
  39596. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39597. }
  39598. this._vertexArrayObjects = {};
  39599. }
  39600. };
  39601. /**
  39602. * Free all associated resources
  39603. */
  39604. Geometry.prototype.dispose = function () {
  39605. var meshes = this._meshes;
  39606. var numOfMeshes = meshes.length;
  39607. var index;
  39608. for (index = 0; index < numOfMeshes; index++) {
  39609. this.releaseForMesh(meshes[index]);
  39610. }
  39611. this._meshes = [];
  39612. this._disposeVertexArrayObjects();
  39613. for (var kind in this._vertexBuffers) {
  39614. this._vertexBuffers[kind].dispose();
  39615. }
  39616. this._vertexBuffers = {};
  39617. this._totalVertices = 0;
  39618. if (this._indexBuffer) {
  39619. this._engine._releaseBuffer(this._indexBuffer);
  39620. }
  39621. this._indexBuffer = null;
  39622. this._indices = [];
  39623. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39624. this.delayLoadingFile = null;
  39625. this._delayLoadingFunction = null;
  39626. this._delayInfo = [];
  39627. this._boundingInfo = null;
  39628. this._scene.removeGeometry(this);
  39629. this._isDisposed = true;
  39630. };
  39631. /**
  39632. * Clone the current geometry into a new geometry
  39633. * @param id defines the unique ID of the new geometry
  39634. * @returns a new geometry object
  39635. */
  39636. Geometry.prototype.copy = function (id) {
  39637. var vertexData = new BABYLON.VertexData();
  39638. vertexData.indices = [];
  39639. var indices = this.getIndices();
  39640. if (indices) {
  39641. for (var index = 0; index < indices.length; index++) {
  39642. vertexData.indices.push(indices[index]);
  39643. }
  39644. }
  39645. var updatable = false;
  39646. var stopChecking = false;
  39647. var kind;
  39648. for (kind in this._vertexBuffers) {
  39649. // using slice() to make a copy of the array and not just reference it
  39650. var data = this.getVerticesData(kind);
  39651. if (data instanceof Float32Array) {
  39652. vertexData.set(new Float32Array(data), kind);
  39653. }
  39654. else {
  39655. vertexData.set(data.slice(0), kind);
  39656. }
  39657. if (!stopChecking) {
  39658. var vb = this.getVertexBuffer(kind);
  39659. if (vb) {
  39660. updatable = vb.isUpdatable();
  39661. stopChecking = !updatable;
  39662. }
  39663. }
  39664. }
  39665. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39666. geometry.delayLoadState = this.delayLoadState;
  39667. geometry.delayLoadingFile = this.delayLoadingFile;
  39668. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39669. for (kind in this._delayInfo) {
  39670. geometry._delayInfo = geometry._delayInfo || [];
  39671. geometry._delayInfo.push(kind);
  39672. }
  39673. // Bounding info
  39674. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39675. return geometry;
  39676. };
  39677. /**
  39678. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39679. * @return a JSON representation of the current geometry data (without the vertices data)
  39680. */
  39681. Geometry.prototype.serialize = function () {
  39682. var serializationObject = {};
  39683. serializationObject.id = this.id;
  39684. serializationObject.updatable = this._updatable;
  39685. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39686. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39687. }
  39688. return serializationObject;
  39689. };
  39690. Geometry.prototype.toNumberArray = function (origin) {
  39691. if (Array.isArray(origin)) {
  39692. return origin;
  39693. }
  39694. else {
  39695. return Array.prototype.slice.call(origin);
  39696. }
  39697. };
  39698. /**
  39699. * Serialize all vertices data into a JSON oject
  39700. * @returns a JSON representation of the current geometry data
  39701. */
  39702. Geometry.prototype.serializeVerticeData = function () {
  39703. var serializationObject = this.serialize();
  39704. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39705. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39706. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39707. serializationObject.positions._updatable = true;
  39708. }
  39709. }
  39710. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39711. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39712. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39713. serializationObject.normals._updatable = true;
  39714. }
  39715. }
  39716. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39717. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39718. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39719. serializationObject.tangets._updatable = true;
  39720. }
  39721. }
  39722. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39723. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39724. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39725. serializationObject.uvs._updatable = true;
  39726. }
  39727. }
  39728. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39729. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39730. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39731. serializationObject.uv2s._updatable = true;
  39732. }
  39733. }
  39734. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39735. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39736. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39737. serializationObject.uv3s._updatable = true;
  39738. }
  39739. }
  39740. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39741. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39742. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39743. serializationObject.uv4s._updatable = true;
  39744. }
  39745. }
  39746. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39747. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39748. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39749. serializationObject.uv5s._updatable = true;
  39750. }
  39751. }
  39752. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39753. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39754. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39755. serializationObject.uv6s._updatable = true;
  39756. }
  39757. }
  39758. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39759. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39760. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39761. serializationObject.colors._updatable = true;
  39762. }
  39763. }
  39764. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39765. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39766. serializationObject.matricesIndices._isExpanded = true;
  39767. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39768. serializationObject.matricesIndices._updatable = true;
  39769. }
  39770. }
  39771. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39772. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39773. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39774. serializationObject.matricesWeights._updatable = true;
  39775. }
  39776. }
  39777. serializationObject.indices = this.toNumberArray(this.getIndices());
  39778. return serializationObject;
  39779. };
  39780. // Statics
  39781. /**
  39782. * Extracts a clone of a mesh geometry
  39783. * @param mesh defines the source mesh
  39784. * @param id defines the unique ID of the new geometry object
  39785. * @returns the new geometry object
  39786. */
  39787. Geometry.ExtractFromMesh = function (mesh, id) {
  39788. var geometry = mesh._geometry;
  39789. if (!geometry) {
  39790. return null;
  39791. }
  39792. return geometry.copy(id);
  39793. };
  39794. /**
  39795. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39796. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39797. * Be aware Math.random() could cause collisions, but:
  39798. * "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"
  39799. * @returns a string containing a new GUID
  39800. */
  39801. Geometry.RandomId = function () {
  39802. return BABYLON.Tools.RandomId();
  39803. };
  39804. /** @hidden */
  39805. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39806. var scene = mesh.getScene();
  39807. // Geometry
  39808. var geometryId = parsedGeometry.geometryId;
  39809. if (geometryId) {
  39810. var geometry = scene.getGeometryByID(geometryId);
  39811. if (geometry) {
  39812. geometry.applyToMesh(mesh);
  39813. }
  39814. }
  39815. else if (parsedGeometry instanceof ArrayBuffer) {
  39816. var binaryInfo = mesh._binaryInfo;
  39817. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39818. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39819. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39820. }
  39821. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39822. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39823. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39824. }
  39825. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39826. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39827. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39828. }
  39829. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39830. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39831. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39832. }
  39833. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39834. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39835. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39836. }
  39837. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39838. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39839. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39840. }
  39841. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39842. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39843. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39844. }
  39845. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39846. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39847. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39848. }
  39849. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39850. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39851. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39852. }
  39853. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39854. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39855. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39856. }
  39857. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39858. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39859. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39860. }
  39861. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39862. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39863. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39864. }
  39865. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39866. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39867. mesh.setIndices(indicesData, null);
  39868. }
  39869. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39870. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39871. mesh.subMeshes = [];
  39872. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39873. var materialIndex = subMeshesData[(i * 5) + 0];
  39874. var verticesStart = subMeshesData[(i * 5) + 1];
  39875. var verticesCount = subMeshesData[(i * 5) + 2];
  39876. var indexStart = subMeshesData[(i * 5) + 3];
  39877. var indexCount = subMeshesData[(i * 5) + 4];
  39878. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39879. }
  39880. }
  39881. }
  39882. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39883. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39884. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39885. if (parsedGeometry.tangents) {
  39886. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39887. }
  39888. if (parsedGeometry.uvs) {
  39889. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39890. }
  39891. if (parsedGeometry.uvs2) {
  39892. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39893. }
  39894. if (parsedGeometry.uvs3) {
  39895. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39896. }
  39897. if (parsedGeometry.uvs4) {
  39898. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39899. }
  39900. if (parsedGeometry.uvs5) {
  39901. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39902. }
  39903. if (parsedGeometry.uvs6) {
  39904. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39905. }
  39906. if (parsedGeometry.colors) {
  39907. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39908. }
  39909. if (parsedGeometry.matricesIndices) {
  39910. if (!parsedGeometry.matricesIndices._isExpanded) {
  39911. var floatIndices = [];
  39912. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39913. var matricesIndex = parsedGeometry.matricesIndices[i];
  39914. floatIndices.push(matricesIndex & 0x000000FF);
  39915. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39916. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39917. floatIndices.push(matricesIndex >> 24);
  39918. }
  39919. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39920. }
  39921. else {
  39922. delete parsedGeometry.matricesIndices._isExpanded;
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39924. }
  39925. }
  39926. if (parsedGeometry.matricesIndicesExtra) {
  39927. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39928. var floatIndices = [];
  39929. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39930. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39931. floatIndices.push(matricesIndex & 0x000000FF);
  39932. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39933. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39934. floatIndices.push(matricesIndex >> 24);
  39935. }
  39936. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39937. }
  39938. else {
  39939. delete parsedGeometry.matricesIndices._isExpanded;
  39940. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39941. }
  39942. }
  39943. if (parsedGeometry.matricesWeights) {
  39944. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39945. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39946. }
  39947. if (parsedGeometry.matricesWeightsExtra) {
  39948. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39949. }
  39950. mesh.setIndices(parsedGeometry.indices, null);
  39951. }
  39952. // SubMeshes
  39953. if (parsedGeometry.subMeshes) {
  39954. mesh.subMeshes = [];
  39955. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39956. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39957. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39958. }
  39959. }
  39960. // Flat shading
  39961. if (mesh._shouldGenerateFlatShading) {
  39962. mesh.convertToFlatShadedMesh();
  39963. delete mesh._shouldGenerateFlatShading;
  39964. }
  39965. // Update
  39966. mesh.computeWorldMatrix(true);
  39967. // Octree
  39968. var sceneOctree = scene.selectionOctree;
  39969. if (sceneOctree !== undefined && sceneOctree !== null) {
  39970. sceneOctree.addMesh(mesh);
  39971. }
  39972. };
  39973. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39974. var epsilon = 1e-3;
  39975. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39976. return;
  39977. }
  39978. var noInfluenceBoneIndex = 0.0;
  39979. if (parsedGeometry.skeletonId > -1) {
  39980. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39981. if (!skeleton) {
  39982. return;
  39983. }
  39984. noInfluenceBoneIndex = skeleton.bones.length;
  39985. }
  39986. else {
  39987. return;
  39988. }
  39989. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39990. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39991. var matricesWeights = parsedGeometry.matricesWeights;
  39992. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39993. var influencers = parsedGeometry.numBoneInfluencer;
  39994. var size = matricesWeights.length;
  39995. for (var i = 0; i < size; i += 4) {
  39996. var weight = 0.0;
  39997. var firstZeroWeight = -1;
  39998. for (var j = 0; j < 4; j++) {
  39999. var w = matricesWeights[i + j];
  40000. weight += w;
  40001. if (w < epsilon && firstZeroWeight < 0) {
  40002. firstZeroWeight = j;
  40003. }
  40004. }
  40005. if (matricesWeightsExtra) {
  40006. for (var j = 0; j < 4; j++) {
  40007. var w = matricesWeightsExtra[i + j];
  40008. weight += w;
  40009. if (w < epsilon && firstZeroWeight < 0) {
  40010. firstZeroWeight = j + 4;
  40011. }
  40012. }
  40013. }
  40014. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40015. firstZeroWeight = influencers - 1;
  40016. }
  40017. if (weight > epsilon) {
  40018. var mweight = 1.0 / weight;
  40019. for (var j = 0; j < 4; j++) {
  40020. matricesWeights[i + j] *= mweight;
  40021. }
  40022. if (matricesWeightsExtra) {
  40023. for (var j = 0; j < 4; j++) {
  40024. matricesWeightsExtra[i + j] *= mweight;
  40025. }
  40026. }
  40027. }
  40028. else {
  40029. if (firstZeroWeight >= 4) {
  40030. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40031. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40032. }
  40033. else {
  40034. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40035. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40036. }
  40037. }
  40038. }
  40039. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40040. if (parsedGeometry.matricesWeightsExtra) {
  40041. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40042. }
  40043. };
  40044. /**
  40045. * Create a new geometry from persisted data (Using .babylon file format)
  40046. * @param parsedVertexData defines the persisted data
  40047. * @param scene defines the hosting scene
  40048. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40049. * @returns the new geometry object
  40050. */
  40051. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40052. if (scene.getGeometryByID(parsedVertexData.id)) {
  40053. return null; // null since geometry could be something else than a box...
  40054. }
  40055. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40056. if (BABYLON.Tags) {
  40057. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40058. }
  40059. if (parsedVertexData.delayLoadingFile) {
  40060. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40061. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40062. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40063. geometry._delayInfo = [];
  40064. if (parsedVertexData.hasUVs) {
  40065. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40066. }
  40067. if (parsedVertexData.hasUVs2) {
  40068. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40069. }
  40070. if (parsedVertexData.hasUVs3) {
  40071. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40072. }
  40073. if (parsedVertexData.hasUVs4) {
  40074. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40075. }
  40076. if (parsedVertexData.hasUVs5) {
  40077. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40078. }
  40079. if (parsedVertexData.hasUVs6) {
  40080. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40081. }
  40082. if (parsedVertexData.hasColors) {
  40083. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40084. }
  40085. if (parsedVertexData.hasMatricesIndices) {
  40086. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40087. }
  40088. if (parsedVertexData.hasMatricesWeights) {
  40089. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40090. }
  40091. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40092. }
  40093. else {
  40094. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40095. }
  40096. scene.pushGeometry(geometry, true);
  40097. return geometry;
  40098. };
  40099. return Geometry;
  40100. }());
  40101. BABYLON.Geometry = Geometry;
  40102. // Primitives
  40103. /// Abstract class
  40104. /**
  40105. * Abstract class used to provide common services for all typed geometries
  40106. * @hidden
  40107. */
  40108. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40109. __extends(_PrimitiveGeometry, _super);
  40110. /**
  40111. * Creates a new typed geometry
  40112. * @param id defines the unique ID of the geometry
  40113. * @param scene defines the hosting scene
  40114. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40115. * @param mesh defines the hosting mesh (can be null)
  40116. */
  40117. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40118. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40119. if (mesh === void 0) { mesh = null; }
  40120. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40121. _this._canBeRegenerated = _canBeRegenerated;
  40122. _this._beingRegenerated = true;
  40123. _this.regenerate();
  40124. _this._beingRegenerated = false;
  40125. return _this;
  40126. }
  40127. /**
  40128. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40129. * @returns true if the geometry can be regenerated
  40130. */
  40131. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40132. return this._canBeRegenerated;
  40133. };
  40134. /**
  40135. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40136. */
  40137. _PrimitiveGeometry.prototype.regenerate = function () {
  40138. if (!this._canBeRegenerated) {
  40139. return;
  40140. }
  40141. this._beingRegenerated = true;
  40142. this.setAllVerticesData(this._regenerateVertexData(), false);
  40143. this._beingRegenerated = false;
  40144. };
  40145. /**
  40146. * Clone the geometry
  40147. * @param id defines the unique ID of the new geometry
  40148. * @returns the new geometry
  40149. */
  40150. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40151. return _super.prototype.copy.call(this, id);
  40152. };
  40153. // overrides
  40154. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40155. if (!this._beingRegenerated) {
  40156. return;
  40157. }
  40158. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40159. };
  40160. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40161. if (!this._beingRegenerated) {
  40162. return;
  40163. }
  40164. _super.prototype.setVerticesData.call(this, kind, data, false);
  40165. };
  40166. // to override
  40167. /** @hidden */
  40168. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40169. throw new Error("Abstract method");
  40170. };
  40171. _PrimitiveGeometry.prototype.copy = function (id) {
  40172. throw new Error("Must be overriden in sub-classes.");
  40173. };
  40174. _PrimitiveGeometry.prototype.serialize = function () {
  40175. var serializationObject = _super.prototype.serialize.call(this);
  40176. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40177. return serializationObject;
  40178. };
  40179. return _PrimitiveGeometry;
  40180. }(Geometry));
  40181. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40182. /**
  40183. * Creates a ribbon geometry
  40184. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40185. */
  40186. var RibbonGeometry = /** @class */ (function (_super) {
  40187. __extends(RibbonGeometry, _super);
  40188. /**
  40189. * Creates a ribbon geometry
  40190. * @param id defines the unique ID of the geometry
  40191. * @param scene defines the hosting scene
  40192. * @param pathArray defines the array of paths to use
  40193. * @param closeArray defines if the last path and the first path must be joined
  40194. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40195. * @param offset defines the offset between points
  40196. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40197. * @param mesh defines the hosting mesh (can be null)
  40198. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40199. */
  40200. function RibbonGeometry(id, scene,
  40201. /**
  40202. * Defines the array of paths to use
  40203. */
  40204. pathArray,
  40205. /**
  40206. * Defines if the last and first points of each path in your pathArray must be joined
  40207. */
  40208. closeArray,
  40209. /**
  40210. * Defines if the last and first points of each path in your pathArray must be joined
  40211. */
  40212. closePath,
  40213. /**
  40214. * Defines the offset between points
  40215. */
  40216. offset, canBeRegenerated, mesh,
  40217. /**
  40218. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40219. */
  40220. side) {
  40221. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40222. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40223. _this.pathArray = pathArray;
  40224. _this.closeArray = closeArray;
  40225. _this.closePath = closePath;
  40226. _this.offset = offset;
  40227. _this.side = side;
  40228. return _this;
  40229. }
  40230. /** @hidden */
  40231. RibbonGeometry.prototype._regenerateVertexData = function () {
  40232. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40233. };
  40234. RibbonGeometry.prototype.copy = function (id) {
  40235. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40236. };
  40237. return RibbonGeometry;
  40238. }(_PrimitiveGeometry));
  40239. BABYLON.RibbonGeometry = RibbonGeometry;
  40240. /**
  40241. * Creates a box geometry
  40242. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40243. */
  40244. var BoxGeometry = /** @class */ (function (_super) {
  40245. __extends(BoxGeometry, _super);
  40246. /**
  40247. * Creates a box geometry
  40248. * @param id defines the unique ID of the geometry
  40249. * @param scene defines the hosting scene
  40250. * @param size defines the zise of the box (width, height and depth are the same)
  40251. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40252. * @param mesh defines the hosting mesh (can be null)
  40253. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40254. */
  40255. function BoxGeometry(id, scene,
  40256. /**
  40257. * Defines the zise of the box (width, height and depth are the same)
  40258. */
  40259. size, canBeRegenerated, mesh,
  40260. /**
  40261. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40262. */
  40263. side) {
  40264. if (mesh === void 0) { mesh = null; }
  40265. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40266. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40267. _this.size = size;
  40268. _this.side = side;
  40269. return _this;
  40270. }
  40271. BoxGeometry.prototype._regenerateVertexData = function () {
  40272. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40273. };
  40274. BoxGeometry.prototype.copy = function (id) {
  40275. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40276. };
  40277. BoxGeometry.prototype.serialize = function () {
  40278. var serializationObject = _super.prototype.serialize.call(this);
  40279. serializationObject.size = this.size;
  40280. return serializationObject;
  40281. };
  40282. BoxGeometry.Parse = function (parsedBox, scene) {
  40283. if (scene.getGeometryByID(parsedBox.id)) {
  40284. return null; // null since geometry could be something else than a box...
  40285. }
  40286. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40287. if (BABYLON.Tags) {
  40288. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40289. }
  40290. scene.pushGeometry(box, true);
  40291. return box;
  40292. };
  40293. return BoxGeometry;
  40294. }(_PrimitiveGeometry));
  40295. BABYLON.BoxGeometry = BoxGeometry;
  40296. /**
  40297. * Creates a sphere geometry
  40298. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40299. */
  40300. var SphereGeometry = /** @class */ (function (_super) {
  40301. __extends(SphereGeometry, _super);
  40302. /**
  40303. * Create a new sphere geometry
  40304. * @param id defines the unique ID of the geometry
  40305. * @param scene defines the hosting scene
  40306. * @param segments defines the number of segments to use to create the sphere
  40307. * @param diameter defines the diameter of the sphere
  40308. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40309. * @param mesh defines the hosting mesh (can be null)
  40310. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40311. */
  40312. function SphereGeometry(id, scene,
  40313. /**
  40314. * Defines the number of segments to use to create the sphere
  40315. */
  40316. segments,
  40317. /**
  40318. * Defines the diameter of the sphere
  40319. */
  40320. diameter, canBeRegenerated, mesh,
  40321. /**
  40322. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40323. */
  40324. side) {
  40325. if (mesh === void 0) { mesh = null; }
  40326. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40327. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40328. _this.segments = segments;
  40329. _this.diameter = diameter;
  40330. _this.side = side;
  40331. return _this;
  40332. }
  40333. SphereGeometry.prototype._regenerateVertexData = function () {
  40334. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40335. };
  40336. SphereGeometry.prototype.copy = function (id) {
  40337. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40338. };
  40339. SphereGeometry.prototype.serialize = function () {
  40340. var serializationObject = _super.prototype.serialize.call(this);
  40341. serializationObject.segments = this.segments;
  40342. serializationObject.diameter = this.diameter;
  40343. return serializationObject;
  40344. };
  40345. SphereGeometry.Parse = function (parsedSphere, scene) {
  40346. if (scene.getGeometryByID(parsedSphere.id)) {
  40347. return null; // null since geometry could be something else than a sphere...
  40348. }
  40349. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40350. if (BABYLON.Tags) {
  40351. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40352. }
  40353. scene.pushGeometry(sphere, true);
  40354. return sphere;
  40355. };
  40356. return SphereGeometry;
  40357. }(_PrimitiveGeometry));
  40358. BABYLON.SphereGeometry = SphereGeometry;
  40359. /**
  40360. * Creates a disc geometry
  40361. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40362. */
  40363. var DiscGeometry = /** @class */ (function (_super) {
  40364. __extends(DiscGeometry, _super);
  40365. /**
  40366. * Creates a new disc geometry
  40367. * @param id defines the unique ID of the geometry
  40368. * @param scene defines the hosting scene
  40369. * @param radius defines the radius of the disc
  40370. * @param tessellation defines the tesselation factor to apply to the disc
  40371. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40372. * @param mesh defines the hosting mesh (can be null)
  40373. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40374. */
  40375. function DiscGeometry(id, scene,
  40376. /**
  40377. * Defines the radius of the disc
  40378. */
  40379. radius,
  40380. /**
  40381. * Defines the tesselation factor to apply to the disc
  40382. */
  40383. tessellation, canBeRegenerated, mesh,
  40384. /**
  40385. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40386. */
  40387. side) {
  40388. if (mesh === void 0) { mesh = null; }
  40389. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40390. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40391. _this.radius = radius;
  40392. _this.tessellation = tessellation;
  40393. _this.side = side;
  40394. return _this;
  40395. }
  40396. DiscGeometry.prototype._regenerateVertexData = function () {
  40397. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40398. };
  40399. DiscGeometry.prototype.copy = function (id) {
  40400. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40401. };
  40402. return DiscGeometry;
  40403. }(_PrimitiveGeometry));
  40404. BABYLON.DiscGeometry = DiscGeometry;
  40405. /**
  40406. * Creates a new cylinder geometry
  40407. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40408. */
  40409. var CylinderGeometry = /** @class */ (function (_super) {
  40410. __extends(CylinderGeometry, _super);
  40411. /**
  40412. * Creates a new cylinder geometry
  40413. * @param id defines the unique ID of the geometry
  40414. * @param scene defines the hosting scene
  40415. * @param height defines the height of the cylinder
  40416. * @param diameterTop defines the diameter of the cylinder's top cap
  40417. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40418. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40419. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40420. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40421. * @param mesh defines the hosting mesh (can be null)
  40422. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40423. */
  40424. function CylinderGeometry(id, scene,
  40425. /**
  40426. * Defines the height of the cylinder
  40427. */
  40428. height,
  40429. /**
  40430. * Defines the diameter of the cylinder's top cap
  40431. */
  40432. diameterTop,
  40433. /**
  40434. * Defines the diameter of the cylinder's bottom cap
  40435. */
  40436. diameterBottom,
  40437. /**
  40438. * Defines the tessellation factor to apply to the cylinder
  40439. */
  40440. tessellation,
  40441. /**
  40442. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40443. */
  40444. subdivisions, canBeRegenerated, mesh,
  40445. /**
  40446. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40447. */
  40448. side) {
  40449. if (subdivisions === void 0) { subdivisions = 1; }
  40450. if (mesh === void 0) { mesh = null; }
  40451. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40452. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40453. _this.height = height;
  40454. _this.diameterTop = diameterTop;
  40455. _this.diameterBottom = diameterBottom;
  40456. _this.tessellation = tessellation;
  40457. _this.subdivisions = subdivisions;
  40458. _this.side = side;
  40459. return _this;
  40460. }
  40461. CylinderGeometry.prototype._regenerateVertexData = function () {
  40462. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40463. };
  40464. CylinderGeometry.prototype.copy = function (id) {
  40465. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40466. };
  40467. CylinderGeometry.prototype.serialize = function () {
  40468. var serializationObject = _super.prototype.serialize.call(this);
  40469. serializationObject.height = this.height;
  40470. serializationObject.diameterTop = this.diameterTop;
  40471. serializationObject.diameterBottom = this.diameterBottom;
  40472. serializationObject.tessellation = this.tessellation;
  40473. return serializationObject;
  40474. };
  40475. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40476. if (scene.getGeometryByID(parsedCylinder.id)) {
  40477. return null; // null since geometry could be something else than a cylinder...
  40478. }
  40479. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40480. if (BABYLON.Tags) {
  40481. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40482. }
  40483. scene.pushGeometry(cylinder, true);
  40484. return cylinder;
  40485. };
  40486. return CylinderGeometry;
  40487. }(_PrimitiveGeometry));
  40488. BABYLON.CylinderGeometry = CylinderGeometry;
  40489. /**
  40490. * Creates a new torus geometry
  40491. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40492. */
  40493. var TorusGeometry = /** @class */ (function (_super) {
  40494. __extends(TorusGeometry, _super);
  40495. /**
  40496. * Creates a new torus geometry
  40497. * @param id defines the unique ID of the geometry
  40498. * @param scene defines the hosting scene
  40499. * @param diameter defines the diameter of the torus
  40500. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40501. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40502. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40503. * @param mesh defines the hosting mesh (can be null)
  40504. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40505. */
  40506. function TorusGeometry(id, scene,
  40507. /**
  40508. * Defines the diameter of the torus
  40509. */
  40510. diameter,
  40511. /**
  40512. * Defines the thickness of the torus (ie. internal diameter)
  40513. */
  40514. thickness,
  40515. /**
  40516. * Defines the tesselation factor to apply to the torus
  40517. */
  40518. tessellation, canBeRegenerated, mesh,
  40519. /**
  40520. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40521. */
  40522. side) {
  40523. if (mesh === void 0) { mesh = null; }
  40524. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40525. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40526. _this.diameter = diameter;
  40527. _this.thickness = thickness;
  40528. _this.tessellation = tessellation;
  40529. _this.side = side;
  40530. return _this;
  40531. }
  40532. TorusGeometry.prototype._regenerateVertexData = function () {
  40533. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40534. };
  40535. TorusGeometry.prototype.copy = function (id) {
  40536. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40537. };
  40538. TorusGeometry.prototype.serialize = function () {
  40539. var serializationObject = _super.prototype.serialize.call(this);
  40540. serializationObject.diameter = this.diameter;
  40541. serializationObject.thickness = this.thickness;
  40542. serializationObject.tessellation = this.tessellation;
  40543. return serializationObject;
  40544. };
  40545. TorusGeometry.Parse = function (parsedTorus, scene) {
  40546. if (scene.getGeometryByID(parsedTorus.id)) {
  40547. return null; // null since geometry could be something else than a torus...
  40548. }
  40549. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40550. if (BABYLON.Tags) {
  40551. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40552. }
  40553. scene.pushGeometry(torus, true);
  40554. return torus;
  40555. };
  40556. return TorusGeometry;
  40557. }(_PrimitiveGeometry));
  40558. BABYLON.TorusGeometry = TorusGeometry;
  40559. /**
  40560. * Creates a new ground geometry
  40561. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40562. */
  40563. var GroundGeometry = /** @class */ (function (_super) {
  40564. __extends(GroundGeometry, _super);
  40565. /**
  40566. * Creates a new ground geometry
  40567. * @param id defines the unique ID of the geometry
  40568. * @param scene defines the hosting scene
  40569. * @param width defines the width of the ground
  40570. * @param height defines the height of the ground
  40571. * @param subdivisions defines the subdivisions to apply to the ground
  40572. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40573. * @param mesh defines the hosting mesh (can be null)
  40574. */
  40575. function GroundGeometry(id, scene,
  40576. /**
  40577. * Defines the width of the ground
  40578. */
  40579. width,
  40580. /**
  40581. * Defines the height of the ground
  40582. */
  40583. height,
  40584. /**
  40585. * Defines the subdivisions to apply to the ground
  40586. */
  40587. subdivisions, canBeRegenerated, mesh) {
  40588. if (mesh === void 0) { mesh = null; }
  40589. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40590. _this.width = width;
  40591. _this.height = height;
  40592. _this.subdivisions = subdivisions;
  40593. return _this;
  40594. }
  40595. GroundGeometry.prototype._regenerateVertexData = function () {
  40596. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40597. };
  40598. GroundGeometry.prototype.copy = function (id) {
  40599. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40600. };
  40601. GroundGeometry.prototype.serialize = function () {
  40602. var serializationObject = _super.prototype.serialize.call(this);
  40603. serializationObject.width = this.width;
  40604. serializationObject.height = this.height;
  40605. serializationObject.subdivisions = this.subdivisions;
  40606. return serializationObject;
  40607. };
  40608. GroundGeometry.Parse = function (parsedGround, scene) {
  40609. if (scene.getGeometryByID(parsedGround.id)) {
  40610. return null; // null since geometry could be something else than a ground...
  40611. }
  40612. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40613. if (BABYLON.Tags) {
  40614. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40615. }
  40616. scene.pushGeometry(ground, true);
  40617. return ground;
  40618. };
  40619. return GroundGeometry;
  40620. }(_PrimitiveGeometry));
  40621. BABYLON.GroundGeometry = GroundGeometry;
  40622. /**
  40623. * Creates a tiled ground geometry
  40624. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40625. */
  40626. var TiledGroundGeometry = /** @class */ (function (_super) {
  40627. __extends(TiledGroundGeometry, _super);
  40628. /**
  40629. * Creates a tiled ground geometry
  40630. * @param id defines the unique ID of the geometry
  40631. * @param scene defines the hosting scene
  40632. * @param xmin defines the minimum value on X axis
  40633. * @param zmin defines the minimum value on Z axis
  40634. * @param xmax defines the maximum value on X axis
  40635. * @param zmax defines the maximum value on Z axis
  40636. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40637. * @param precision defines the precision to use when computing the tiles
  40638. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40639. * @param mesh defines the hosting mesh (can be null)
  40640. */
  40641. function TiledGroundGeometry(id, scene,
  40642. /**
  40643. * Defines the minimum value on X axis
  40644. */
  40645. xmin,
  40646. /**
  40647. * Defines the minimum value on Z axis
  40648. */
  40649. zmin,
  40650. /**
  40651. * Defines the maximum value on X axis
  40652. */
  40653. xmax,
  40654. /**
  40655. * Defines the maximum value on Z axis
  40656. */
  40657. zmax,
  40658. /**
  40659. * Defines the subdivisions to apply to the ground
  40660. */
  40661. subdivisions,
  40662. /**
  40663. * Defines the precision to use when computing the tiles
  40664. */
  40665. precision, canBeRegenerated, mesh) {
  40666. if (mesh === void 0) { mesh = null; }
  40667. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40668. _this.xmin = xmin;
  40669. _this.zmin = zmin;
  40670. _this.xmax = xmax;
  40671. _this.zmax = zmax;
  40672. _this.subdivisions = subdivisions;
  40673. _this.precision = precision;
  40674. return _this;
  40675. }
  40676. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40677. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40678. };
  40679. TiledGroundGeometry.prototype.copy = function (id) {
  40680. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40681. };
  40682. return TiledGroundGeometry;
  40683. }(_PrimitiveGeometry));
  40684. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40685. /**
  40686. * Creates a plane geometry
  40687. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40688. */
  40689. var PlaneGeometry = /** @class */ (function (_super) {
  40690. __extends(PlaneGeometry, _super);
  40691. /**
  40692. * Creates a plane geometry
  40693. * @param id defines the unique ID of the geometry
  40694. * @param scene defines the hosting scene
  40695. * @param size defines the size of the plane (width === height)
  40696. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40697. * @param mesh defines the hosting mesh (can be null)
  40698. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40699. */
  40700. function PlaneGeometry(id, scene,
  40701. /**
  40702. * Defines the size of the plane (width === height)
  40703. */
  40704. size, canBeRegenerated, mesh,
  40705. /**
  40706. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40707. */
  40708. side) {
  40709. if (mesh === void 0) { mesh = null; }
  40710. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40711. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40712. _this.size = size;
  40713. _this.side = side;
  40714. return _this;
  40715. }
  40716. PlaneGeometry.prototype._regenerateVertexData = function () {
  40717. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40718. };
  40719. PlaneGeometry.prototype.copy = function (id) {
  40720. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40721. };
  40722. PlaneGeometry.prototype.serialize = function () {
  40723. var serializationObject = _super.prototype.serialize.call(this);
  40724. serializationObject.size = this.size;
  40725. return serializationObject;
  40726. };
  40727. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40728. if (scene.getGeometryByID(parsedPlane.id)) {
  40729. return null; // null since geometry could be something else than a ground...
  40730. }
  40731. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40732. if (BABYLON.Tags) {
  40733. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40734. }
  40735. scene.pushGeometry(plane, true);
  40736. return plane;
  40737. };
  40738. return PlaneGeometry;
  40739. }(_PrimitiveGeometry));
  40740. BABYLON.PlaneGeometry = PlaneGeometry;
  40741. /**
  40742. * Creates a torus knot geometry
  40743. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40744. */
  40745. var TorusKnotGeometry = /** @class */ (function (_super) {
  40746. __extends(TorusKnotGeometry, _super);
  40747. /**
  40748. * Creates a torus knot geometry
  40749. * @param id defines the unique ID of the geometry
  40750. * @param scene defines the hosting scene
  40751. * @param radius defines the radius of the torus knot
  40752. * @param tube defines the thickness of the torus knot tube
  40753. * @param radialSegments defines the number of radial segments
  40754. * @param tubularSegments defines the number of tubular segments
  40755. * @param p defines the first number of windings
  40756. * @param q defines the second number of windings
  40757. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40758. * @param mesh defines the hosting mesh (can be null)
  40759. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40760. */
  40761. function TorusKnotGeometry(id, scene,
  40762. /**
  40763. * Defines the radius of the torus knot
  40764. */
  40765. radius,
  40766. /**
  40767. * Defines the thickness of the torus knot tube
  40768. */
  40769. tube,
  40770. /**
  40771. * Defines the number of radial segments
  40772. */
  40773. radialSegments,
  40774. /**
  40775. * Defines the number of tubular segments
  40776. */
  40777. tubularSegments,
  40778. /**
  40779. * Defines the first number of windings
  40780. */
  40781. p,
  40782. /**
  40783. * Defines the second number of windings
  40784. */
  40785. q, canBeRegenerated, mesh,
  40786. /**
  40787. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40788. */
  40789. side) {
  40790. if (mesh === void 0) { mesh = null; }
  40791. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40792. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40793. _this.radius = radius;
  40794. _this.tube = tube;
  40795. _this.radialSegments = radialSegments;
  40796. _this.tubularSegments = tubularSegments;
  40797. _this.p = p;
  40798. _this.q = q;
  40799. _this.side = side;
  40800. return _this;
  40801. }
  40802. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40803. 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 });
  40804. };
  40805. TorusKnotGeometry.prototype.copy = function (id) {
  40806. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40807. };
  40808. TorusKnotGeometry.prototype.serialize = function () {
  40809. var serializationObject = _super.prototype.serialize.call(this);
  40810. serializationObject.radius = this.radius;
  40811. serializationObject.tube = this.tube;
  40812. serializationObject.radialSegments = this.radialSegments;
  40813. serializationObject.tubularSegments = this.tubularSegments;
  40814. serializationObject.p = this.p;
  40815. serializationObject.q = this.q;
  40816. return serializationObject;
  40817. };
  40818. ;
  40819. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40820. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40821. return null; // null since geometry could be something else than a ground...
  40822. }
  40823. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40824. if (BABYLON.Tags) {
  40825. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40826. }
  40827. scene.pushGeometry(torusKnot, true);
  40828. return torusKnot;
  40829. };
  40830. return TorusKnotGeometry;
  40831. }(_PrimitiveGeometry));
  40832. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40833. //}
  40834. })(BABYLON || (BABYLON = {}));
  40835. //# sourceMappingURL=babylon.geometry.js.map
  40836. var BABYLON;
  40837. (function (BABYLON) {
  40838. /**
  40839. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40840. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40841. */
  40842. var PostProcessManager = /** @class */ (function () {
  40843. /**
  40844. * Creates a new instance PostProcess
  40845. * @param scene The scene that the post process is associated with.
  40846. */
  40847. function PostProcessManager(scene) {
  40848. this._vertexBuffers = {};
  40849. this._scene = scene;
  40850. }
  40851. PostProcessManager.prototype._prepareBuffers = function () {
  40852. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40853. return;
  40854. }
  40855. // VBO
  40856. var vertices = [];
  40857. vertices.push(1, 1);
  40858. vertices.push(-1, 1);
  40859. vertices.push(-1, -1);
  40860. vertices.push(1, -1);
  40861. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40862. this._buildIndexBuffer();
  40863. };
  40864. PostProcessManager.prototype._buildIndexBuffer = function () {
  40865. // Indices
  40866. var indices = [];
  40867. indices.push(0);
  40868. indices.push(1);
  40869. indices.push(2);
  40870. indices.push(0);
  40871. indices.push(2);
  40872. indices.push(3);
  40873. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40874. };
  40875. /**
  40876. * Rebuilds the vertex buffers of the manager.
  40877. */
  40878. PostProcessManager.prototype._rebuild = function () {
  40879. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40880. if (!vb) {
  40881. return;
  40882. }
  40883. vb._rebuild();
  40884. this._buildIndexBuffer();
  40885. };
  40886. // Methods
  40887. /**
  40888. * Prepares a frame to be run through a post process.
  40889. * @param sourceTexture The input texture to the post procesess. (default: null)
  40890. * @param postProcesses An array of post processes to be run. (default: null)
  40891. * @returns True if the post processes were able to be run.
  40892. */
  40893. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40894. if (sourceTexture === void 0) { sourceTexture = null; }
  40895. if (postProcesses === void 0) { postProcesses = null; }
  40896. var camera = this._scene.activeCamera;
  40897. if (!camera) {
  40898. return false;
  40899. }
  40900. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40901. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40902. return false;
  40903. }
  40904. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40905. return true;
  40906. };
  40907. /**
  40908. * Manually render a set of post processes to a texture.
  40909. * @param postProcesses An array of post processes to be run.
  40910. * @param targetTexture The target texture to render to.
  40911. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40912. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  40913. * @param lodLevel defines which lod of the texture to render to
  40914. */
  40915. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  40916. if (targetTexture === void 0) { targetTexture = null; }
  40917. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40918. if (faceIndex === void 0) { faceIndex = 0; }
  40919. if (lodLevel === void 0) { lodLevel = 0; }
  40920. var engine = this._scene.getEngine();
  40921. for (var index = 0; index < postProcesses.length; index++) {
  40922. if (index < postProcesses.length - 1) {
  40923. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40924. }
  40925. else {
  40926. if (targetTexture) {
  40927. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  40928. }
  40929. else {
  40930. engine.restoreDefaultFramebuffer();
  40931. }
  40932. }
  40933. var pp = postProcesses[index];
  40934. var effect = pp.apply();
  40935. if (effect) {
  40936. pp.onBeforeRenderObservable.notifyObservers(effect);
  40937. // VBOs
  40938. this._prepareBuffers();
  40939. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40940. // Draw order
  40941. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40942. pp.onAfterRenderObservable.notifyObservers(effect);
  40943. }
  40944. }
  40945. // Restore depth buffer
  40946. engine.setDepthBuffer(true);
  40947. engine.setDepthWrite(true);
  40948. };
  40949. /**
  40950. * Finalize the result of the output of the postprocesses.
  40951. * @param doNotPresent If true the result will not be displayed to the screen.
  40952. * @param targetTexture The target texture to render to.
  40953. * @param faceIndex The index of the face to bind the target texture to.
  40954. * @param postProcesses The array of post processes to render.
  40955. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40956. */
  40957. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40958. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40959. var camera = this._scene.activeCamera;
  40960. if (!camera) {
  40961. return;
  40962. }
  40963. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40964. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40965. return;
  40966. }
  40967. var engine = this._scene.getEngine();
  40968. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40969. var pp = postProcesses[index];
  40970. if (index < len - 1) {
  40971. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40972. }
  40973. else {
  40974. if (targetTexture) {
  40975. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40976. pp._outputTexture = targetTexture;
  40977. }
  40978. else {
  40979. engine.restoreDefaultFramebuffer();
  40980. pp._outputTexture = null;
  40981. }
  40982. }
  40983. if (doNotPresent) {
  40984. break;
  40985. }
  40986. var effect = pp.apply();
  40987. if (effect) {
  40988. pp.onBeforeRenderObservable.notifyObservers(effect);
  40989. // VBOs
  40990. this._prepareBuffers();
  40991. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40992. // Draw order
  40993. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40994. pp.onAfterRenderObservable.notifyObservers(effect);
  40995. }
  40996. }
  40997. // Restore states
  40998. engine.setDepthBuffer(true);
  40999. engine.setDepthWrite(true);
  41000. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41001. };
  41002. /**
  41003. * Disposes of the post process manager.
  41004. */
  41005. PostProcessManager.prototype.dispose = function () {
  41006. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  41007. if (buffer) {
  41008. buffer.dispose();
  41009. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  41010. }
  41011. if (this._indexBuffer) {
  41012. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41013. this._indexBuffer = null;
  41014. }
  41015. };
  41016. return PostProcessManager;
  41017. }());
  41018. BABYLON.PostProcessManager = PostProcessManager;
  41019. })(BABYLON || (BABYLON = {}));
  41020. //# sourceMappingURL=babylon.postProcessManager.js.map
  41021. var BABYLON;
  41022. (function (BABYLON) {
  41023. /**
  41024. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41025. */
  41026. var PerformanceMonitor = /** @class */ (function () {
  41027. /**
  41028. * constructor
  41029. * @param frameSampleSize The number of samples required to saturate the sliding window
  41030. */
  41031. function PerformanceMonitor(frameSampleSize) {
  41032. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41033. this._enabled = true;
  41034. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41035. }
  41036. /**
  41037. * Samples current frame
  41038. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41039. */
  41040. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41041. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41042. if (!this._enabled)
  41043. return;
  41044. if (this._lastFrameTimeMs != null) {
  41045. var dt = timeMs - this._lastFrameTimeMs;
  41046. this._rollingFrameTime.add(dt);
  41047. }
  41048. this._lastFrameTimeMs = timeMs;
  41049. };
  41050. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41051. /**
  41052. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41053. * @return Average frame time in milliseconds
  41054. */
  41055. get: function () {
  41056. return this._rollingFrameTime.average;
  41057. },
  41058. enumerable: true,
  41059. configurable: true
  41060. });
  41061. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41062. /**
  41063. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41064. * @return Frame time variance in milliseconds squared
  41065. */
  41066. get: function () {
  41067. return this._rollingFrameTime.variance;
  41068. },
  41069. enumerable: true,
  41070. configurable: true
  41071. });
  41072. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41073. /**
  41074. * Returns the frame time of the most recent frame
  41075. * @return Frame time in milliseconds
  41076. */
  41077. get: function () {
  41078. return this._rollingFrameTime.history(0);
  41079. },
  41080. enumerable: true,
  41081. configurable: true
  41082. });
  41083. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41084. /**
  41085. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41086. * @return Framerate in frames per second
  41087. */
  41088. get: function () {
  41089. return 1000.0 / this._rollingFrameTime.average;
  41090. },
  41091. enumerable: true,
  41092. configurable: true
  41093. });
  41094. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41095. /**
  41096. * Returns the average framerate in frames per second using the most recent frame time
  41097. * @return Framerate in frames per second
  41098. */
  41099. get: function () {
  41100. var history = this._rollingFrameTime.history(0);
  41101. if (history === 0) {
  41102. return 0;
  41103. }
  41104. return 1000.0 / history;
  41105. },
  41106. enumerable: true,
  41107. configurable: true
  41108. });
  41109. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41110. /**
  41111. * Returns true if enough samples have been taken to completely fill the sliding window
  41112. * @return true if saturated
  41113. */
  41114. get: function () {
  41115. return this._rollingFrameTime.isSaturated();
  41116. },
  41117. enumerable: true,
  41118. configurable: true
  41119. });
  41120. /**
  41121. * Enables contributions to the sliding window sample set
  41122. */
  41123. PerformanceMonitor.prototype.enable = function () {
  41124. this._enabled = true;
  41125. };
  41126. /**
  41127. * Disables contributions to the sliding window sample set
  41128. * Samples will not be interpolated over the disabled period
  41129. */
  41130. PerformanceMonitor.prototype.disable = function () {
  41131. this._enabled = false;
  41132. //clear last sample to avoid interpolating over the disabled period when next enabled
  41133. this._lastFrameTimeMs = null;
  41134. };
  41135. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41136. /**
  41137. * Returns true if sampling is enabled
  41138. * @return true if enabled
  41139. */
  41140. get: function () {
  41141. return this._enabled;
  41142. },
  41143. enumerable: true,
  41144. configurable: true
  41145. });
  41146. /**
  41147. * Resets performance monitor
  41148. */
  41149. PerformanceMonitor.prototype.reset = function () {
  41150. //clear last sample to avoid interpolating over the disabled period when next enabled
  41151. this._lastFrameTimeMs = null;
  41152. //wipe record
  41153. this._rollingFrameTime.reset();
  41154. };
  41155. return PerformanceMonitor;
  41156. }());
  41157. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41158. /**
  41159. * RollingAverage
  41160. *
  41161. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41162. */
  41163. var RollingAverage = /** @class */ (function () {
  41164. /**
  41165. * constructor
  41166. * @param length The number of samples required to saturate the sliding window
  41167. */
  41168. function RollingAverage(length) {
  41169. this._samples = new Array(length);
  41170. this.reset();
  41171. }
  41172. /**
  41173. * Adds a sample to the sample set
  41174. * @param v The sample value
  41175. */
  41176. RollingAverage.prototype.add = function (v) {
  41177. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41178. var delta;
  41179. //we need to check if we've already wrapped round
  41180. if (this.isSaturated()) {
  41181. //remove bottom of stack from mean
  41182. var bottomValue = this._samples[this._pos];
  41183. delta = bottomValue - this.average;
  41184. this.average -= delta / (this._sampleCount - 1);
  41185. this._m2 -= delta * (bottomValue - this.average);
  41186. }
  41187. else {
  41188. this._sampleCount++;
  41189. }
  41190. //add new value to mean
  41191. delta = v - this.average;
  41192. this.average += delta / (this._sampleCount);
  41193. this._m2 += delta * (v - this.average);
  41194. //set the new variance
  41195. this.variance = this._m2 / (this._sampleCount - 1);
  41196. this._samples[this._pos] = v;
  41197. this._pos++;
  41198. this._pos %= this._samples.length; //positive wrap around
  41199. };
  41200. /**
  41201. * Returns previously added values or null if outside of history or outside the sliding window domain
  41202. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41203. * @return Value previously recorded with add() or null if outside of range
  41204. */
  41205. RollingAverage.prototype.history = function (i) {
  41206. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41207. return 0;
  41208. }
  41209. var i0 = this._wrapPosition(this._pos - 1.0);
  41210. return this._samples[this._wrapPosition(i0 - i)];
  41211. };
  41212. /**
  41213. * Returns true if enough samples have been taken to completely fill the sliding window
  41214. * @return true if sample-set saturated
  41215. */
  41216. RollingAverage.prototype.isSaturated = function () {
  41217. return this._sampleCount >= this._samples.length;
  41218. };
  41219. /**
  41220. * Resets the rolling average (equivalent to 0 samples taken so far)
  41221. */
  41222. RollingAverage.prototype.reset = function () {
  41223. this.average = 0;
  41224. this.variance = 0;
  41225. this._sampleCount = 0;
  41226. this._pos = 0;
  41227. this._m2 = 0;
  41228. };
  41229. /**
  41230. * Wraps a value around the sample range boundaries
  41231. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41232. * @return Wrapped position in sample range
  41233. */
  41234. RollingAverage.prototype._wrapPosition = function (i) {
  41235. var max = this._samples.length;
  41236. return ((i % max) + max) % max;
  41237. };
  41238. return RollingAverage;
  41239. }());
  41240. BABYLON.RollingAverage = RollingAverage;
  41241. })(BABYLON || (BABYLON = {}));
  41242. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41243. var BABYLON;
  41244. (function (BABYLON) {
  41245. /**
  41246. * This groups together the common properties used for image processing either in direct forward pass
  41247. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41248. * or not.
  41249. */
  41250. var ImageProcessingConfiguration = /** @class */ (function () {
  41251. function ImageProcessingConfiguration() {
  41252. /**
  41253. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41254. */
  41255. this.colorCurves = new BABYLON.ColorCurves();
  41256. this._colorCurvesEnabled = false;
  41257. this._colorGradingEnabled = false;
  41258. this._colorGradingWithGreenDepth = true;
  41259. this._colorGradingBGR = true;
  41260. this._exposure = 1.0;
  41261. this._toneMappingEnabled = false;
  41262. this._contrast = 1.0;
  41263. /**
  41264. * Vignette stretch size.
  41265. */
  41266. this.vignetteStretch = 0;
  41267. /**
  41268. * Vignette centre X Offset.
  41269. */
  41270. this.vignetteCentreX = 0;
  41271. /**
  41272. * Vignette centre Y Offset.
  41273. */
  41274. this.vignetteCentreY = 0;
  41275. /**
  41276. * Vignette weight or intensity of the vignette effect.
  41277. */
  41278. this.vignetteWeight = 1.5;
  41279. /**
  41280. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41281. * if vignetteEnabled is set to true.
  41282. */
  41283. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41284. /**
  41285. * Camera field of view used by the Vignette effect.
  41286. */
  41287. this.vignetteCameraFov = 0.5;
  41288. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41289. this._vignetteEnabled = false;
  41290. this._applyByPostProcess = false;
  41291. this._isEnabled = true;
  41292. /**
  41293. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41294. */
  41295. this.onUpdateParameters = new BABYLON.Observable();
  41296. }
  41297. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41298. /**
  41299. * Gets wether the color curves effect is enabled.
  41300. */
  41301. get: function () {
  41302. return this._colorCurvesEnabled;
  41303. },
  41304. /**
  41305. * Sets wether the color curves effect is enabled.
  41306. */
  41307. set: function (value) {
  41308. if (this._colorCurvesEnabled === value) {
  41309. return;
  41310. }
  41311. this._colorCurvesEnabled = value;
  41312. this._updateParameters();
  41313. },
  41314. enumerable: true,
  41315. configurable: true
  41316. });
  41317. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41318. /**
  41319. * Gets wether the color grading effect is enabled.
  41320. */
  41321. get: function () {
  41322. return this._colorGradingEnabled;
  41323. },
  41324. /**
  41325. * Sets wether the color grading effect is enabled.
  41326. */
  41327. set: function (value) {
  41328. if (this._colorGradingEnabled === value) {
  41329. return;
  41330. }
  41331. this._colorGradingEnabled = value;
  41332. this._updateParameters();
  41333. },
  41334. enumerable: true,
  41335. configurable: true
  41336. });
  41337. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41338. /**
  41339. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41340. */
  41341. get: function () {
  41342. return this._colorGradingWithGreenDepth;
  41343. },
  41344. /**
  41345. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41346. */
  41347. set: function (value) {
  41348. if (this._colorGradingWithGreenDepth === value) {
  41349. return;
  41350. }
  41351. this._colorGradingWithGreenDepth = value;
  41352. this._updateParameters();
  41353. },
  41354. enumerable: true,
  41355. configurable: true
  41356. });
  41357. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41358. /**
  41359. * Gets wether the color grading texture contains BGR values.
  41360. */
  41361. get: function () {
  41362. return this._colorGradingBGR;
  41363. },
  41364. /**
  41365. * Sets wether the color grading texture contains BGR values.
  41366. */
  41367. set: function (value) {
  41368. if (this._colorGradingBGR === value) {
  41369. return;
  41370. }
  41371. this._colorGradingBGR = value;
  41372. this._updateParameters();
  41373. },
  41374. enumerable: true,
  41375. configurable: true
  41376. });
  41377. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41378. /**
  41379. * Gets the Exposure used in the effect.
  41380. */
  41381. get: function () {
  41382. return this._exposure;
  41383. },
  41384. /**
  41385. * Sets the Exposure used in the effect.
  41386. */
  41387. set: function (value) {
  41388. if (this._exposure === value) {
  41389. return;
  41390. }
  41391. this._exposure = value;
  41392. this._updateParameters();
  41393. },
  41394. enumerable: true,
  41395. configurable: true
  41396. });
  41397. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41398. /**
  41399. * Gets wether the tone mapping effect is enabled.
  41400. */
  41401. get: function () {
  41402. return this._toneMappingEnabled;
  41403. },
  41404. /**
  41405. * Sets wether the tone mapping effect is enabled.
  41406. */
  41407. set: function (value) {
  41408. if (this._toneMappingEnabled === value) {
  41409. return;
  41410. }
  41411. this._toneMappingEnabled = value;
  41412. this._updateParameters();
  41413. },
  41414. enumerable: true,
  41415. configurable: true
  41416. });
  41417. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41418. /**
  41419. * Gets the contrast used in the effect.
  41420. */
  41421. get: function () {
  41422. return this._contrast;
  41423. },
  41424. /**
  41425. * Sets the contrast used in the effect.
  41426. */
  41427. set: function (value) {
  41428. if (this._contrast === value) {
  41429. return;
  41430. }
  41431. this._contrast = value;
  41432. this._updateParameters();
  41433. },
  41434. enumerable: true,
  41435. configurable: true
  41436. });
  41437. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41438. /**
  41439. * Gets the vignette blend mode allowing different kind of effect.
  41440. */
  41441. get: function () {
  41442. return this._vignetteBlendMode;
  41443. },
  41444. /**
  41445. * Sets the vignette blend mode allowing different kind of effect.
  41446. */
  41447. set: function (value) {
  41448. if (this._vignetteBlendMode === value) {
  41449. return;
  41450. }
  41451. this._vignetteBlendMode = value;
  41452. this._updateParameters();
  41453. },
  41454. enumerable: true,
  41455. configurable: true
  41456. });
  41457. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41458. /**
  41459. * Gets wether the vignette effect is enabled.
  41460. */
  41461. get: function () {
  41462. return this._vignetteEnabled;
  41463. },
  41464. /**
  41465. * Sets wether the vignette effect is enabled.
  41466. */
  41467. set: function (value) {
  41468. if (this._vignetteEnabled === value) {
  41469. return;
  41470. }
  41471. this._vignetteEnabled = value;
  41472. this._updateParameters();
  41473. },
  41474. enumerable: true,
  41475. configurable: true
  41476. });
  41477. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41478. /**
  41479. * Gets wether the image processing is applied through a post process or not.
  41480. */
  41481. get: function () {
  41482. return this._applyByPostProcess;
  41483. },
  41484. /**
  41485. * Sets wether the image processing is applied through a post process or not.
  41486. */
  41487. set: function (value) {
  41488. if (this._applyByPostProcess === value) {
  41489. return;
  41490. }
  41491. this._applyByPostProcess = value;
  41492. this._updateParameters();
  41493. },
  41494. enumerable: true,
  41495. configurable: true
  41496. });
  41497. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41498. /**
  41499. * Gets wether the image processing is enabled or not.
  41500. */
  41501. get: function () {
  41502. return this._isEnabled;
  41503. },
  41504. /**
  41505. * Sets wether the image processing is enabled or not.
  41506. */
  41507. set: function (value) {
  41508. if (this._isEnabled === value) {
  41509. return;
  41510. }
  41511. this._isEnabled = value;
  41512. this._updateParameters();
  41513. },
  41514. enumerable: true,
  41515. configurable: true
  41516. });
  41517. /**
  41518. * Method called each time the image processing information changes requires to recompile the effect.
  41519. */
  41520. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41521. this.onUpdateParameters.notifyObservers(this);
  41522. };
  41523. ImageProcessingConfiguration.prototype.getClassName = function () {
  41524. return "ImageProcessingConfiguration";
  41525. };
  41526. /**
  41527. * Prepare the list of uniforms associated with the Image Processing effects.
  41528. * @param uniformsList The list of uniforms used in the effect
  41529. * @param defines the list of defines currently in use
  41530. */
  41531. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41532. if (defines.EXPOSURE) {
  41533. uniforms.push("exposureLinear");
  41534. }
  41535. if (defines.CONTRAST) {
  41536. uniforms.push("contrast");
  41537. }
  41538. if (defines.COLORGRADING) {
  41539. uniforms.push("colorTransformSettings");
  41540. }
  41541. if (defines.VIGNETTE) {
  41542. uniforms.push("vInverseScreenSize");
  41543. uniforms.push("vignetteSettings1");
  41544. uniforms.push("vignetteSettings2");
  41545. }
  41546. if (defines.COLORCURVES) {
  41547. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41548. }
  41549. };
  41550. /**
  41551. * Prepare the list of samplers associated with the Image Processing effects.
  41552. * @param uniformsList The list of uniforms used in the effect
  41553. * @param defines the list of defines currently in use
  41554. */
  41555. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41556. if (defines.COLORGRADING) {
  41557. samplersList.push("txColorTransform");
  41558. }
  41559. };
  41560. /**
  41561. * Prepare the list of defines associated to the shader.
  41562. * @param defines the list of defines to complete
  41563. */
  41564. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41565. if (forPostProcess === void 0) { forPostProcess = false; }
  41566. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41567. defines.VIGNETTE = false;
  41568. defines.TONEMAPPING = false;
  41569. defines.CONTRAST = false;
  41570. defines.EXPOSURE = false;
  41571. defines.COLORCURVES = false;
  41572. defines.COLORGRADING = false;
  41573. defines.COLORGRADING3D = false;
  41574. defines.IMAGEPROCESSING = false;
  41575. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41576. return;
  41577. }
  41578. defines.VIGNETTE = this.vignetteEnabled;
  41579. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41580. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41581. defines.TONEMAPPING = this.toneMappingEnabled;
  41582. defines.CONTRAST = (this.contrast !== 1.0);
  41583. defines.EXPOSURE = (this.exposure !== 1.0);
  41584. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41585. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41586. if (defines.COLORGRADING) {
  41587. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41588. }
  41589. else {
  41590. defines.COLORGRADING3D = false;
  41591. }
  41592. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41593. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41594. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41595. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41596. };
  41597. /**
  41598. * Returns true if all the image processing information are ready.
  41599. */
  41600. ImageProcessingConfiguration.prototype.isReady = function () {
  41601. // Color Grading texure can not be none blocking.
  41602. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41603. };
  41604. /**
  41605. * Binds the image processing to the shader.
  41606. * @param effect The effect to bind to
  41607. */
  41608. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41609. if (aspectRatio === void 0) { aspectRatio = 1; }
  41610. // Color Curves
  41611. if (this._colorCurvesEnabled && this.colorCurves) {
  41612. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41613. }
  41614. // Vignette
  41615. if (this._vignetteEnabled) {
  41616. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41617. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41618. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41619. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41620. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41621. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41622. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41623. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41624. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41625. var vignettePower = -2.0 * this.vignetteWeight;
  41626. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41627. }
  41628. // Exposure
  41629. effect.setFloat("exposureLinear", this.exposure);
  41630. // Contrast
  41631. effect.setFloat("contrast", this.contrast);
  41632. // Color transform settings
  41633. if (this.colorGradingTexture) {
  41634. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41635. var textureSize = this.colorGradingTexture.getSize().height;
  41636. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41637. 0.5 / textureSize, // textureOffset
  41638. textureSize, // textureSize
  41639. this.colorGradingTexture.level // weight
  41640. );
  41641. }
  41642. };
  41643. /**
  41644. * Clones the current image processing instance.
  41645. * @return The cloned image processing
  41646. */
  41647. ImageProcessingConfiguration.prototype.clone = function () {
  41648. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41649. };
  41650. /**
  41651. * Serializes the current image processing instance to a json representation.
  41652. * @return a JSON representation
  41653. */
  41654. ImageProcessingConfiguration.prototype.serialize = function () {
  41655. return BABYLON.SerializationHelper.Serialize(this);
  41656. };
  41657. /**
  41658. * Parses the image processing from a json representation.
  41659. * @param source the JSON source to parse
  41660. * @return The parsed image processing
  41661. */
  41662. ImageProcessingConfiguration.Parse = function (source) {
  41663. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41664. };
  41665. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41666. /**
  41667. * Used to apply the vignette as a mix with the pixel color.
  41668. */
  41669. get: function () {
  41670. return this._VIGNETTEMODE_MULTIPLY;
  41671. },
  41672. enumerable: true,
  41673. configurable: true
  41674. });
  41675. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41676. /**
  41677. * Used to apply the vignette as a replacement of the pixel color.
  41678. */
  41679. get: function () {
  41680. return this._VIGNETTEMODE_OPAQUE;
  41681. },
  41682. enumerable: true,
  41683. configurable: true
  41684. });
  41685. // Static constants associated to the image processing.
  41686. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41687. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41688. __decorate([
  41689. BABYLON.serializeAsColorCurves()
  41690. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41691. __decorate([
  41692. BABYLON.serialize()
  41693. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41694. __decorate([
  41695. BABYLON.serializeAsTexture()
  41696. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41697. __decorate([
  41698. BABYLON.serialize()
  41699. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41700. __decorate([
  41701. BABYLON.serialize()
  41702. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41703. __decorate([
  41704. BABYLON.serialize()
  41705. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41706. __decorate([
  41707. BABYLON.serialize()
  41708. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41709. __decorate([
  41710. BABYLON.serialize()
  41711. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41712. __decorate([
  41713. BABYLON.serialize()
  41714. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41715. __decorate([
  41716. BABYLON.serialize()
  41717. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41718. __decorate([
  41719. BABYLON.serialize()
  41720. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41721. __decorate([
  41722. BABYLON.serialize()
  41723. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41724. __decorate([
  41725. BABYLON.serialize()
  41726. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41727. __decorate([
  41728. BABYLON.serializeAsColor4()
  41729. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41730. __decorate([
  41731. BABYLON.serialize()
  41732. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41733. __decorate([
  41734. BABYLON.serialize()
  41735. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41736. __decorate([
  41737. BABYLON.serialize()
  41738. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41739. __decorate([
  41740. BABYLON.serialize()
  41741. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41742. __decorate([
  41743. BABYLON.serialize()
  41744. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41745. return ImageProcessingConfiguration;
  41746. }());
  41747. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41748. })(BABYLON || (BABYLON = {}));
  41749. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41750. var BABYLON;
  41751. (function (BABYLON) {
  41752. /**
  41753. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41754. * It can help converting any input color in a desired output one. This can then be used to create effects
  41755. * from sepia, black and white to sixties or futuristic rendering...
  41756. *
  41757. * The only supported format is currently 3dl.
  41758. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41759. */
  41760. var ColorGradingTexture = /** @class */ (function (_super) {
  41761. __extends(ColorGradingTexture, _super);
  41762. /**
  41763. * Instantiates a ColorGradingTexture from the following parameters.
  41764. *
  41765. * @param url The location of the color gradind data (currently only supporting 3dl)
  41766. * @param scene The scene the texture will be used in
  41767. */
  41768. function ColorGradingTexture(url, scene) {
  41769. var _this = _super.call(this, scene) || this;
  41770. if (!url) {
  41771. return _this;
  41772. }
  41773. _this._engine = scene.getEngine();
  41774. _this._textureMatrix = BABYLON.Matrix.Identity();
  41775. _this.name = url;
  41776. _this.url = url;
  41777. _this.hasAlpha = false;
  41778. _this.isCube = false;
  41779. _this.is3D = _this._engine.webGLVersion > 1;
  41780. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41781. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41782. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41783. _this.anisotropicFilteringLevel = 1;
  41784. _this._texture = _this._getFromCache(url, true);
  41785. if (!_this._texture) {
  41786. if (!scene.useDelayedTextureLoading) {
  41787. _this.loadTexture();
  41788. }
  41789. else {
  41790. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41791. }
  41792. }
  41793. return _this;
  41794. }
  41795. /**
  41796. * Returns the texture matrix used in most of the material.
  41797. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41798. */
  41799. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41800. return this._textureMatrix;
  41801. };
  41802. /**
  41803. * Occurs when the file being loaded is a .3dl LUT file.
  41804. */
  41805. ColorGradingTexture.prototype.load3dlTexture = function () {
  41806. var engine = this._engine;
  41807. var texture;
  41808. if (engine.webGLVersion === 1) {
  41809. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41810. }
  41811. else {
  41812. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41813. }
  41814. this._texture = texture;
  41815. var callback = function (text) {
  41816. if (typeof text !== "string") {
  41817. return;
  41818. }
  41819. var data = null;
  41820. var tempData = null;
  41821. var line;
  41822. var lines = text.split('\n');
  41823. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41824. var maxColor = 0;
  41825. for (var i = 0; i < lines.length; i++) {
  41826. line = lines[i];
  41827. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41828. continue;
  41829. if (line.indexOf('#') === 0)
  41830. continue;
  41831. var words = line.split(" ");
  41832. if (size === 0) {
  41833. // Number of space + one
  41834. size = words.length;
  41835. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41836. tempData = new Float32Array(size * size * size * 4);
  41837. continue;
  41838. }
  41839. if (size != 0) {
  41840. var r = Math.max(parseInt(words[0]), 0);
  41841. var g = Math.max(parseInt(words[1]), 0);
  41842. var b = Math.max(parseInt(words[2]), 0);
  41843. maxColor = Math.max(r, maxColor);
  41844. maxColor = Math.max(g, maxColor);
  41845. maxColor = Math.max(b, maxColor);
  41846. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41847. if (tempData) {
  41848. tempData[pixelStorageIndex + 0] = r;
  41849. tempData[pixelStorageIndex + 1] = g;
  41850. tempData[pixelStorageIndex + 2] = b;
  41851. }
  41852. pixelIndexSlice++;
  41853. if (pixelIndexSlice % size == 0) {
  41854. pixelIndexH++;
  41855. pixelIndexSlice = 0;
  41856. if (pixelIndexH % size == 0) {
  41857. pixelIndexW++;
  41858. pixelIndexH = 0;
  41859. }
  41860. }
  41861. }
  41862. }
  41863. if (tempData && data) {
  41864. for (var i = 0; i < tempData.length; i++) {
  41865. if (i > 0 && (i + 1) % 4 === 0) {
  41866. data[i] = 255;
  41867. }
  41868. else {
  41869. var value = tempData[i];
  41870. data[i] = (value / maxColor * 255);
  41871. }
  41872. }
  41873. }
  41874. if (texture.is3D) {
  41875. texture.updateSize(size, size, size);
  41876. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41877. }
  41878. else {
  41879. texture.updateSize(size * size, size);
  41880. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41881. }
  41882. };
  41883. var scene = this.getScene();
  41884. if (scene) {
  41885. scene._loadFile(this.url, callback);
  41886. }
  41887. else {
  41888. this._engine._loadFile(this.url, callback);
  41889. }
  41890. return this._texture;
  41891. };
  41892. /**
  41893. * Starts the loading process of the texture.
  41894. */
  41895. ColorGradingTexture.prototype.loadTexture = function () {
  41896. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41897. this.load3dlTexture();
  41898. }
  41899. };
  41900. /**
  41901. * Clones the color gradind texture.
  41902. */
  41903. ColorGradingTexture.prototype.clone = function () {
  41904. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41905. // Base texture
  41906. newTexture.level = this.level;
  41907. return newTexture;
  41908. };
  41909. /**
  41910. * Called during delayed load for textures.
  41911. */
  41912. ColorGradingTexture.prototype.delayLoad = function () {
  41913. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41914. return;
  41915. }
  41916. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41917. this._texture = this._getFromCache(this.url, true);
  41918. if (!this._texture) {
  41919. this.loadTexture();
  41920. }
  41921. };
  41922. /**
  41923. * Parses a color grading texture serialized by Babylon.
  41924. * @param parsedTexture The texture information being parsedTexture
  41925. * @param scene The scene to load the texture in
  41926. * @param rootUrl The root url of the data assets to load
  41927. * @return A color gradind texture
  41928. */
  41929. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41930. var texture = null;
  41931. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41932. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41933. texture.name = parsedTexture.name;
  41934. texture.level = parsedTexture.level;
  41935. }
  41936. return texture;
  41937. };
  41938. /**
  41939. * Serializes the LUT texture to json format.
  41940. */
  41941. ColorGradingTexture.prototype.serialize = function () {
  41942. if (!this.name) {
  41943. return null;
  41944. }
  41945. var serializationObject = {};
  41946. serializationObject.name = this.name;
  41947. serializationObject.level = this.level;
  41948. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41949. return serializationObject;
  41950. };
  41951. /**
  41952. * Empty line regex stored for GC.
  41953. */
  41954. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41955. return ColorGradingTexture;
  41956. }(BABYLON.BaseTexture));
  41957. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41958. })(BABYLON || (BABYLON = {}));
  41959. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41960. var BABYLON;
  41961. (function (BABYLON) {
  41962. /**
  41963. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41964. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41965. * 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;
  41966. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41967. */
  41968. var ColorCurves = /** @class */ (function () {
  41969. function ColorCurves() {
  41970. this._dirty = true;
  41971. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41972. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41973. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41974. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41975. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41976. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41977. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41978. this._globalHue = 30;
  41979. this._globalDensity = 0;
  41980. this._globalSaturation = 0;
  41981. this._globalExposure = 0;
  41982. this._highlightsHue = 30;
  41983. this._highlightsDensity = 0;
  41984. this._highlightsSaturation = 0;
  41985. this._highlightsExposure = 0;
  41986. this._midtonesHue = 30;
  41987. this._midtonesDensity = 0;
  41988. this._midtonesSaturation = 0;
  41989. this._midtonesExposure = 0;
  41990. this._shadowsHue = 30;
  41991. this._shadowsDensity = 0;
  41992. this._shadowsSaturation = 0;
  41993. this._shadowsExposure = 0;
  41994. }
  41995. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41996. /**
  41997. * Gets the global Hue value.
  41998. * 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).
  41999. */
  42000. get: function () {
  42001. return this._globalHue;
  42002. },
  42003. /**
  42004. * Sets the global Hue value.
  42005. * 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).
  42006. */
  42007. set: function (value) {
  42008. this._globalHue = value;
  42009. this._dirty = true;
  42010. },
  42011. enumerable: true,
  42012. configurable: true
  42013. });
  42014. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  42015. /**
  42016. * Gets the global Density value.
  42017. * 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.
  42018. * Values less than zero provide a filter of opposite hue.
  42019. */
  42020. get: function () {
  42021. return this._globalDensity;
  42022. },
  42023. /**
  42024. * Sets the global Density value.
  42025. * 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.
  42026. * Values less than zero provide a filter of opposite hue.
  42027. */
  42028. set: function (value) {
  42029. this._globalDensity = value;
  42030. this._dirty = true;
  42031. },
  42032. enumerable: true,
  42033. configurable: true
  42034. });
  42035. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  42036. /**
  42037. * Gets the global Saturation value.
  42038. * 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.
  42039. */
  42040. get: function () {
  42041. return this._globalSaturation;
  42042. },
  42043. /**
  42044. * Sets the global Saturation value.
  42045. * 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.
  42046. */
  42047. set: function (value) {
  42048. this._globalSaturation = value;
  42049. this._dirty = true;
  42050. },
  42051. enumerable: true,
  42052. configurable: true
  42053. });
  42054. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  42055. /**
  42056. * Gets the global Exposure value.
  42057. * 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.
  42058. */
  42059. get: function () {
  42060. return this._globalExposure;
  42061. },
  42062. /**
  42063. * Sets the global Exposure value.
  42064. * 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.
  42065. */
  42066. set: function (value) {
  42067. this._globalExposure = value;
  42068. this._dirty = true;
  42069. },
  42070. enumerable: true,
  42071. configurable: true
  42072. });
  42073. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  42074. /**
  42075. * Gets the highlights Hue value.
  42076. * 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).
  42077. */
  42078. get: function () {
  42079. return this._highlightsHue;
  42080. },
  42081. /**
  42082. * Sets the highlights Hue value.
  42083. * 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).
  42084. */
  42085. set: function (value) {
  42086. this._highlightsHue = value;
  42087. this._dirty = true;
  42088. },
  42089. enumerable: true,
  42090. configurable: true
  42091. });
  42092. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  42093. /**
  42094. * Gets the highlights Density value.
  42095. * 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.
  42096. * Values less than zero provide a filter of opposite hue.
  42097. */
  42098. get: function () {
  42099. return this._highlightsDensity;
  42100. },
  42101. /**
  42102. * Sets the highlights Density value.
  42103. * 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.
  42104. * Values less than zero provide a filter of opposite hue.
  42105. */
  42106. set: function (value) {
  42107. this._highlightsDensity = value;
  42108. this._dirty = true;
  42109. },
  42110. enumerable: true,
  42111. configurable: true
  42112. });
  42113. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  42114. /**
  42115. * Gets the highlights Saturation value.
  42116. * 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.
  42117. */
  42118. get: function () {
  42119. return this._highlightsSaturation;
  42120. },
  42121. /**
  42122. * Sets the highlights Saturation value.
  42123. * 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.
  42124. */
  42125. set: function (value) {
  42126. this._highlightsSaturation = value;
  42127. this._dirty = true;
  42128. },
  42129. enumerable: true,
  42130. configurable: true
  42131. });
  42132. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42133. /**
  42134. * Gets the highlights Exposure value.
  42135. * 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.
  42136. */
  42137. get: function () {
  42138. return this._highlightsExposure;
  42139. },
  42140. /**
  42141. * Sets the highlights Exposure value.
  42142. * 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.
  42143. */
  42144. set: function (value) {
  42145. this._highlightsExposure = value;
  42146. this._dirty = true;
  42147. },
  42148. enumerable: true,
  42149. configurable: true
  42150. });
  42151. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42152. /**
  42153. * Gets the midtones Hue value.
  42154. * 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).
  42155. */
  42156. get: function () {
  42157. return this._midtonesHue;
  42158. },
  42159. /**
  42160. * Sets the midtones Hue value.
  42161. * 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).
  42162. */
  42163. set: function (value) {
  42164. this._midtonesHue = value;
  42165. this._dirty = true;
  42166. },
  42167. enumerable: true,
  42168. configurable: true
  42169. });
  42170. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42171. /**
  42172. * Gets the midtones Density value.
  42173. * 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.
  42174. * Values less than zero provide a filter of opposite hue.
  42175. */
  42176. get: function () {
  42177. return this._midtonesDensity;
  42178. },
  42179. /**
  42180. * Sets the midtones Density value.
  42181. * 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.
  42182. * Values less than zero provide a filter of opposite hue.
  42183. */
  42184. set: function (value) {
  42185. this._midtonesDensity = value;
  42186. this._dirty = true;
  42187. },
  42188. enumerable: true,
  42189. configurable: true
  42190. });
  42191. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42192. /**
  42193. * Gets the midtones Saturation value.
  42194. * 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.
  42195. */
  42196. get: function () {
  42197. return this._midtonesSaturation;
  42198. },
  42199. /**
  42200. * Sets the midtones Saturation value.
  42201. * 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.
  42202. */
  42203. set: function (value) {
  42204. this._midtonesSaturation = value;
  42205. this._dirty = true;
  42206. },
  42207. enumerable: true,
  42208. configurable: true
  42209. });
  42210. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42211. /**
  42212. * Gets the midtones Exposure value.
  42213. * 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.
  42214. */
  42215. get: function () {
  42216. return this._midtonesExposure;
  42217. },
  42218. /**
  42219. * Sets the midtones Exposure value.
  42220. * 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.
  42221. */
  42222. set: function (value) {
  42223. this._midtonesExposure = value;
  42224. this._dirty = true;
  42225. },
  42226. enumerable: true,
  42227. configurable: true
  42228. });
  42229. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42230. /**
  42231. * Gets the shadows Hue value.
  42232. * 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).
  42233. */
  42234. get: function () {
  42235. return this._shadowsHue;
  42236. },
  42237. /**
  42238. * Sets the shadows Hue value.
  42239. * 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).
  42240. */
  42241. set: function (value) {
  42242. this._shadowsHue = value;
  42243. this._dirty = true;
  42244. },
  42245. enumerable: true,
  42246. configurable: true
  42247. });
  42248. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42249. /**
  42250. * Gets the shadows Density value.
  42251. * 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.
  42252. * Values less than zero provide a filter of opposite hue.
  42253. */
  42254. get: function () {
  42255. return this._shadowsDensity;
  42256. },
  42257. /**
  42258. * Sets the shadows Density value.
  42259. * 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.
  42260. * Values less than zero provide a filter of opposite hue.
  42261. */
  42262. set: function (value) {
  42263. this._shadowsDensity = value;
  42264. this._dirty = true;
  42265. },
  42266. enumerable: true,
  42267. configurable: true
  42268. });
  42269. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42270. /**
  42271. * Gets the shadows Saturation value.
  42272. * 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.
  42273. */
  42274. get: function () {
  42275. return this._shadowsSaturation;
  42276. },
  42277. /**
  42278. * Sets the shadows Saturation value.
  42279. * 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.
  42280. */
  42281. set: function (value) {
  42282. this._shadowsSaturation = value;
  42283. this._dirty = true;
  42284. },
  42285. enumerable: true,
  42286. configurable: true
  42287. });
  42288. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42289. /**
  42290. * Gets the shadows Exposure value.
  42291. * 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.
  42292. */
  42293. get: function () {
  42294. return this._shadowsExposure;
  42295. },
  42296. /**
  42297. * Sets the shadows Exposure value.
  42298. * 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.
  42299. */
  42300. set: function (value) {
  42301. this._shadowsExposure = value;
  42302. this._dirty = true;
  42303. },
  42304. enumerable: true,
  42305. configurable: true
  42306. });
  42307. ColorCurves.prototype.getClassName = function () {
  42308. return "ColorCurves";
  42309. };
  42310. /**
  42311. * Binds the color curves to the shader.
  42312. * @param colorCurves The color curve to bind
  42313. * @param effect The effect to bind to
  42314. */
  42315. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42316. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42317. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42318. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42319. if (colorCurves._dirty) {
  42320. colorCurves._dirty = false;
  42321. // Fill in global info.
  42322. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42323. // Compute highlights info.
  42324. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42325. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42326. // Compute midtones info.
  42327. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42328. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42329. // Compute shadows info.
  42330. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42331. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42332. // Compute deltas (neutral is midtones).
  42333. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42334. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42335. }
  42336. if (effect) {
  42337. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42338. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42339. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42340. }
  42341. };
  42342. /**
  42343. * Prepare the list of uniforms associated with the ColorCurves effects.
  42344. * @param uniformsList The list of uniforms used in the effect
  42345. */
  42346. ColorCurves.PrepareUniforms = function (uniformsList) {
  42347. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42348. };
  42349. /**
  42350. * Returns color grading data based on a hue, density, saturation and exposure value.
  42351. * @param filterHue The hue of the color filter.
  42352. * @param filterDensity The density of the color filter.
  42353. * @param saturation The saturation.
  42354. * @param exposure The exposure.
  42355. * @param result The result data container.
  42356. */
  42357. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42358. if (hue == null) {
  42359. return;
  42360. }
  42361. hue = ColorCurves.clamp(hue, 0, 360);
  42362. density = ColorCurves.clamp(density, -100, 100);
  42363. saturation = ColorCurves.clamp(saturation, -100, 100);
  42364. exposure = ColorCurves.clamp(exposure, -100, 100);
  42365. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42366. // so that the maximum filter density is only 50% control. This provides fine control
  42367. // for small values and reasonable range.
  42368. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42369. density *= 0.5;
  42370. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42371. if (density < 0) {
  42372. density *= -1;
  42373. hue = (hue + 180) % 360;
  42374. }
  42375. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42376. result.scaleToRef(2, result);
  42377. result.a = 1 + 0.01 * saturation;
  42378. };
  42379. /**
  42380. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42381. * @param value The input slider value in range [-100,100].
  42382. * @returns Adjusted value.
  42383. */
  42384. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42385. value /= 100;
  42386. var x = Math.abs(value);
  42387. x = Math.pow(x, 2);
  42388. if (value < 0) {
  42389. x *= -1;
  42390. }
  42391. x *= 100;
  42392. return x;
  42393. };
  42394. /**
  42395. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42396. * @param hue The hue (H) input.
  42397. * @param saturation The saturation (S) input.
  42398. * @param brightness The brightness (B) input.
  42399. * @result An RGBA color represented as Vector4.
  42400. */
  42401. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42402. var h = ColorCurves.clamp(hue, 0, 360);
  42403. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42404. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42405. if (s === 0) {
  42406. result.r = v;
  42407. result.g = v;
  42408. result.b = v;
  42409. }
  42410. else {
  42411. // sector 0 to 5
  42412. h /= 60;
  42413. var i = Math.floor(h);
  42414. // fractional part of h
  42415. var f = h - i;
  42416. var p = v * (1 - s);
  42417. var q = v * (1 - s * f);
  42418. var t = v * (1 - s * (1 - f));
  42419. switch (i) {
  42420. case 0:
  42421. result.r = v;
  42422. result.g = t;
  42423. result.b = p;
  42424. break;
  42425. case 1:
  42426. result.r = q;
  42427. result.g = v;
  42428. result.b = p;
  42429. break;
  42430. case 2:
  42431. result.r = p;
  42432. result.g = v;
  42433. result.b = t;
  42434. break;
  42435. case 3:
  42436. result.r = p;
  42437. result.g = q;
  42438. result.b = v;
  42439. break;
  42440. case 4:
  42441. result.r = t;
  42442. result.g = p;
  42443. result.b = v;
  42444. break;
  42445. default: // case 5:
  42446. result.r = v;
  42447. result.g = p;
  42448. result.b = q;
  42449. break;
  42450. }
  42451. }
  42452. result.a = 1;
  42453. };
  42454. /**
  42455. * Returns a value clamped between min and max
  42456. * @param value The value to clamp
  42457. * @param min The minimum of value
  42458. * @param max The maximum of value
  42459. * @returns The clamped value.
  42460. */
  42461. ColorCurves.clamp = function (value, min, max) {
  42462. return Math.min(Math.max(value, min), max);
  42463. };
  42464. /**
  42465. * Clones the current color curve instance.
  42466. * @return The cloned curves
  42467. */
  42468. ColorCurves.prototype.clone = function () {
  42469. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42470. };
  42471. /**
  42472. * Serializes the current color curve instance to a json representation.
  42473. * @return a JSON representation
  42474. */
  42475. ColorCurves.prototype.serialize = function () {
  42476. return BABYLON.SerializationHelper.Serialize(this);
  42477. };
  42478. /**
  42479. * Parses the color curve from a json representation.
  42480. * @param source the JSON source to parse
  42481. * @return The parsed curves
  42482. */
  42483. ColorCurves.Parse = function (source) {
  42484. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42485. };
  42486. __decorate([
  42487. BABYLON.serialize()
  42488. ], ColorCurves.prototype, "_globalHue", void 0);
  42489. __decorate([
  42490. BABYLON.serialize()
  42491. ], ColorCurves.prototype, "_globalDensity", void 0);
  42492. __decorate([
  42493. BABYLON.serialize()
  42494. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42495. __decorate([
  42496. BABYLON.serialize()
  42497. ], ColorCurves.prototype, "_globalExposure", void 0);
  42498. __decorate([
  42499. BABYLON.serialize()
  42500. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42501. __decorate([
  42502. BABYLON.serialize()
  42503. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42504. __decorate([
  42505. BABYLON.serialize()
  42506. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42507. __decorate([
  42508. BABYLON.serialize()
  42509. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42510. __decorate([
  42511. BABYLON.serialize()
  42512. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42513. __decorate([
  42514. BABYLON.serialize()
  42515. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42516. __decorate([
  42517. BABYLON.serialize()
  42518. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42519. __decorate([
  42520. BABYLON.serialize()
  42521. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42522. return ColorCurves;
  42523. }());
  42524. BABYLON.ColorCurves = ColorCurves;
  42525. })(BABYLON || (BABYLON = {}));
  42526. //# sourceMappingURL=babylon.colorCurves.js.map
  42527. //# sourceMappingURL=babylon.behavior.js.map
  42528. var BABYLON;
  42529. (function (BABYLON) {
  42530. /**
  42531. * "Static Class" containing the most commonly used helper while dealing with material for
  42532. * rendering purpose.
  42533. *
  42534. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42535. *
  42536. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42537. */
  42538. var MaterialHelper = /** @class */ (function () {
  42539. function MaterialHelper() {
  42540. }
  42541. /**
  42542. * Bind the current view position to an effect.
  42543. * @param effect The effect to be bound
  42544. * @param scene The scene the eyes position is used from
  42545. */
  42546. MaterialHelper.BindEyePosition = function (effect, scene) {
  42547. if (scene._forcedViewPosition) {
  42548. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42549. return;
  42550. }
  42551. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42552. };
  42553. /**
  42554. * Helps preparing the defines values about the UVs in used in the effect.
  42555. * UVs are shared as much as we can accross chanels in the shaders.
  42556. * @param texture The texture we are preparing the UVs for
  42557. * @param defines The defines to update
  42558. * @param key The chanel key "diffuse", "specular"... used in the shader
  42559. */
  42560. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42561. defines._needUVs = true;
  42562. defines[key] = true;
  42563. if (texture.getTextureMatrix().isIdentity(true)) {
  42564. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42565. if (texture.coordinatesIndex === 0) {
  42566. defines["MAINUV1"] = true;
  42567. }
  42568. else {
  42569. defines["MAINUV2"] = true;
  42570. }
  42571. }
  42572. else {
  42573. defines[key + "DIRECTUV"] = 0;
  42574. }
  42575. };
  42576. /**
  42577. * Binds a texture matrix value to its corrsponding uniform
  42578. * @param texture The texture to bind the matrix for
  42579. * @param uniformBuffer The uniform buffer receivin the data
  42580. * @param key The chanel key "diffuse", "specular"... used in the shader
  42581. */
  42582. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42583. var matrix = texture.getTextureMatrix();
  42584. if (!matrix.isIdentity(true)) {
  42585. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42586. }
  42587. };
  42588. /**
  42589. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42590. * @param mesh defines the current mesh
  42591. * @param scene defines the current scene
  42592. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42593. * @param pointsCloud defines if point cloud rendering has to be turned on
  42594. * @param fogEnabled defines if fog has to be turned on
  42595. * @param alphaTest defines if alpha testing has to be turned on
  42596. * @param defines defines the current list of defines
  42597. */
  42598. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42599. if (defines._areMiscDirty) {
  42600. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42601. defines["POINTSIZE"] = pointsCloud;
  42602. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42603. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42604. defines["ALPHATEST"] = alphaTest;
  42605. }
  42606. };
  42607. /**
  42608. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42609. * @param scene defines the current scene
  42610. * @param engine defines the current engine
  42611. * @param defines specifies the list of active defines
  42612. * @param useInstances defines if instances have to be turned on
  42613. * @param useClipPlane defines if clip plane have to be turned on
  42614. */
  42615. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42616. if (useClipPlane === void 0) { useClipPlane = null; }
  42617. var changed = false;
  42618. if (useClipPlane == null) {
  42619. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42620. }
  42621. if (defines["CLIPPLANE"] !== useClipPlane) {
  42622. defines["CLIPPLANE"] = useClipPlane;
  42623. changed = true;
  42624. }
  42625. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42626. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42627. changed = true;
  42628. }
  42629. if (defines["INSTANCES"] !== useInstances) {
  42630. defines["INSTANCES"] = useInstances;
  42631. changed = true;
  42632. }
  42633. if (changed) {
  42634. defines.markAsUnprocessed();
  42635. }
  42636. };
  42637. /**
  42638. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42639. * @param mesh The mesh containing the geometry data we will draw
  42640. * @param defines The defines to update
  42641. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42642. * @param useBones Precise whether bones should be used or not (override mesh info)
  42643. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42644. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42645. * @returns false if defines are considered not dirty and have not been checked
  42646. */
  42647. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42648. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42649. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42650. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42651. return false;
  42652. }
  42653. defines._normals = defines._needNormals;
  42654. defines._uvs = defines._needUVs;
  42655. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42656. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42657. defines["TANGENT"] = true;
  42658. }
  42659. if (defines._needUVs) {
  42660. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42661. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42662. }
  42663. else {
  42664. defines["UV1"] = false;
  42665. defines["UV2"] = false;
  42666. }
  42667. if (useVertexColor) {
  42668. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42669. defines["VERTEXCOLOR"] = hasVertexColors;
  42670. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42671. }
  42672. if (useBones) {
  42673. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42674. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42675. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42676. }
  42677. else {
  42678. defines["NUM_BONE_INFLUENCERS"] = 0;
  42679. defines["BonesPerMesh"] = 0;
  42680. }
  42681. }
  42682. if (useMorphTargets) {
  42683. var manager = mesh.morphTargetManager;
  42684. if (manager) {
  42685. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42686. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42687. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42688. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42689. }
  42690. else {
  42691. defines["MORPHTARGETS_TANGENT"] = false;
  42692. defines["MORPHTARGETS_NORMAL"] = false;
  42693. defines["MORPHTARGETS"] = false;
  42694. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42695. }
  42696. }
  42697. return true;
  42698. };
  42699. /**
  42700. * Prepares the defines related to the light information passed in parameter
  42701. * @param scene The scene we are intending to draw
  42702. * @param mesh The mesh the effect is compiling for
  42703. * @param defines The defines to update
  42704. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42705. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42706. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42707. * @returns true if normals will be required for the rest of the effect
  42708. */
  42709. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42710. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42711. if (disableLighting === void 0) { disableLighting = false; }
  42712. if (!defines._areLightsDirty) {
  42713. return defines._needNormals;
  42714. }
  42715. var lightIndex = 0;
  42716. var needNormals = false;
  42717. var needRebuild = false;
  42718. var lightmapMode = false;
  42719. var shadowEnabled = false;
  42720. var specularEnabled = false;
  42721. if (scene.lightsEnabled && !disableLighting) {
  42722. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42723. var light = _a[_i];
  42724. needNormals = true;
  42725. if (defines["LIGHT" + lightIndex] === undefined) {
  42726. needRebuild = true;
  42727. }
  42728. defines["LIGHT" + lightIndex] = true;
  42729. defines["SPOTLIGHT" + lightIndex] = false;
  42730. defines["HEMILIGHT" + lightIndex] = false;
  42731. defines["POINTLIGHT" + lightIndex] = false;
  42732. defines["DIRLIGHT" + lightIndex] = false;
  42733. var type;
  42734. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42735. type = "SPOTLIGHT" + lightIndex;
  42736. var spotLight = light;
  42737. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42738. }
  42739. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42740. type = "HEMILIGHT" + lightIndex;
  42741. }
  42742. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42743. type = "POINTLIGHT" + lightIndex;
  42744. }
  42745. else {
  42746. type = "DIRLIGHT" + lightIndex;
  42747. }
  42748. defines[type] = true;
  42749. // Specular
  42750. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42751. specularEnabled = true;
  42752. }
  42753. // Shadows
  42754. defines["SHADOW" + lightIndex] = false;
  42755. defines["SHADOWPCF" + lightIndex] = false;
  42756. defines["SHADOWPCSS" + lightIndex] = false;
  42757. defines["SHADOWPOISSON" + lightIndex] = false;
  42758. defines["SHADOWESM" + lightIndex] = false;
  42759. defines["SHADOWCUBE" + lightIndex] = false;
  42760. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42761. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42762. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42763. var shadowGenerator = light.getShadowGenerator();
  42764. if (shadowGenerator) {
  42765. shadowEnabled = true;
  42766. shadowGenerator.prepareDefines(defines, lightIndex);
  42767. }
  42768. }
  42769. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42770. lightmapMode = true;
  42771. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42772. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42773. }
  42774. else {
  42775. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42776. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42777. }
  42778. lightIndex++;
  42779. if (lightIndex === maxSimultaneousLights)
  42780. break;
  42781. }
  42782. }
  42783. defines["SPECULARTERM"] = specularEnabled;
  42784. defines["SHADOWS"] = shadowEnabled;
  42785. // Resetting all other lights if any
  42786. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42787. if (defines["LIGHT" + index] !== undefined) {
  42788. defines["LIGHT" + index] = false;
  42789. defines["HEMILIGHT" + lightIndex] = false;
  42790. defines["POINTLIGHT" + lightIndex] = false;
  42791. defines["DIRLIGHT" + lightIndex] = false;
  42792. defines["SPOTLIGHT" + lightIndex] = false;
  42793. defines["SHADOW" + lightIndex] = false;
  42794. }
  42795. }
  42796. var caps = scene.getEngine().getCaps();
  42797. if (defines["SHADOWFLOAT"] === undefined) {
  42798. needRebuild = true;
  42799. }
  42800. defines["SHADOWFLOAT"] = shadowEnabled &&
  42801. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42802. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42803. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42804. if (needRebuild) {
  42805. defines.rebuild();
  42806. }
  42807. return needNormals;
  42808. };
  42809. /**
  42810. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42811. * that won t be acctive due to defines being turned off.
  42812. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42813. * @param samplersList The samplers list
  42814. * @param defines The defines helping in the list generation
  42815. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42816. */
  42817. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42818. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42819. var uniformsList;
  42820. var uniformBuffersList = null;
  42821. if (uniformsListOrOptions.uniformsNames) {
  42822. var options = uniformsListOrOptions;
  42823. uniformsList = options.uniformsNames;
  42824. uniformBuffersList = options.uniformBuffersNames;
  42825. samplersList = options.samplers;
  42826. defines = options.defines;
  42827. maxSimultaneousLights = options.maxSimultaneousLights;
  42828. }
  42829. else {
  42830. uniformsList = uniformsListOrOptions;
  42831. if (!samplersList) {
  42832. samplersList = [];
  42833. }
  42834. }
  42835. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42836. if (!defines["LIGHT" + lightIndex]) {
  42837. break;
  42838. }
  42839. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42840. if (uniformBuffersList) {
  42841. uniformBuffersList.push("Light" + lightIndex);
  42842. }
  42843. samplersList.push("shadowSampler" + lightIndex);
  42844. samplersList.push("depthSampler" + lightIndex);
  42845. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42846. samplersList.push("projectionLightSampler" + lightIndex);
  42847. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42848. }
  42849. }
  42850. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42851. uniformsList.push("morphTargetInfluences");
  42852. }
  42853. };
  42854. /**
  42855. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42856. * @param defines The defines to update while falling back
  42857. * @param fallbacks The authorized effect fallbacks
  42858. * @param maxSimultaneousLights The maximum number of lights allowed
  42859. * @param rank the current rank of the Effect
  42860. * @returns The newly affected rank
  42861. */
  42862. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42863. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42864. if (rank === void 0) { rank = 0; }
  42865. var lightFallbackRank = 0;
  42866. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42867. if (!defines["LIGHT" + lightIndex]) {
  42868. break;
  42869. }
  42870. if (lightIndex > 0) {
  42871. lightFallbackRank = rank + lightIndex;
  42872. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42873. }
  42874. if (!defines["SHADOWS"]) {
  42875. if (defines["SHADOW" + lightIndex]) {
  42876. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42877. }
  42878. if (defines["SHADOWPCF" + lightIndex]) {
  42879. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42880. }
  42881. if (defines["SHADOWPCSS" + lightIndex]) {
  42882. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42883. }
  42884. if (defines["SHADOWPOISSON" + lightIndex]) {
  42885. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42886. }
  42887. if (defines["SHADOWESM" + lightIndex]) {
  42888. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42889. }
  42890. }
  42891. }
  42892. return lightFallbackRank++;
  42893. };
  42894. /**
  42895. * Prepares the list of attributes required for morph targets according to the effect defines.
  42896. * @param attribs The current list of supported attribs
  42897. * @param mesh The mesh to prepare the morph targets attributes for
  42898. * @param defines The current Defines of the effect
  42899. */
  42900. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42901. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42902. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42903. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42904. var manager = mesh.morphTargetManager;
  42905. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42906. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42907. for (var index = 0; index < influencers; index++) {
  42908. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42909. if (normal) {
  42910. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42911. }
  42912. if (tangent) {
  42913. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42914. }
  42915. if (attribs.length > maxAttributesCount) {
  42916. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42917. }
  42918. }
  42919. }
  42920. };
  42921. /**
  42922. * Prepares the list of attributes required for bones according to the effect defines.
  42923. * @param attribs The current list of supported attribs
  42924. * @param mesh The mesh to prepare the bones attributes for
  42925. * @param defines The current Defines of the effect
  42926. * @param fallbacks The current efffect fallback strategy
  42927. */
  42928. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42929. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42930. fallbacks.addCPUSkinningFallback(0, mesh);
  42931. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42932. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42933. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42934. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42935. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42936. }
  42937. }
  42938. };
  42939. /**
  42940. * Prepares the list of attributes required for instances according to the effect defines.
  42941. * @param attribs The current list of supported attribs
  42942. * @param defines The current Defines of the effect
  42943. */
  42944. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42945. if (defines["INSTANCES"]) {
  42946. attribs.push("world0");
  42947. attribs.push("world1");
  42948. attribs.push("world2");
  42949. attribs.push("world3");
  42950. }
  42951. };
  42952. /**
  42953. * Binds the light shadow information to the effect for the given mesh.
  42954. * @param light The light containing the generator
  42955. * @param scene The scene the lights belongs to
  42956. * @param mesh The mesh we are binding the information to render
  42957. * @param lightIndex The light index in the effect used to render the mesh
  42958. * @param effect The effect we are binding the data to
  42959. */
  42960. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42961. if (light.shadowEnabled && mesh.receiveShadows) {
  42962. var shadowGenerator = light.getShadowGenerator();
  42963. if (shadowGenerator) {
  42964. shadowGenerator.bindShadowLight(lightIndex, effect);
  42965. }
  42966. }
  42967. };
  42968. /**
  42969. * Binds the light information to the effect.
  42970. * @param light The light containing the generator
  42971. * @param effect The effect we are binding the data to
  42972. * @param lightIndex The light index in the effect used to render
  42973. */
  42974. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42975. light.transferToEffect(effect, lightIndex + "");
  42976. };
  42977. /**
  42978. * Binds the lights information from the scene to the effect for the given mesh.
  42979. * @param scene The scene the lights belongs to
  42980. * @param mesh The mesh we are binding the information to render
  42981. * @param effect The effect we are binding the data to
  42982. * @param defines The generated defines for the effect
  42983. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42984. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42985. */
  42986. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42987. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42988. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42989. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42990. for (var i = 0; i < len; i++) {
  42991. var light = mesh._lightSources[i];
  42992. var iAsString = i.toString();
  42993. var scaledIntensity = light.getScaledIntensity();
  42994. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42995. MaterialHelper.BindLightProperties(light, effect, i);
  42996. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42997. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42998. if (defines["SPECULARTERM"]) {
  42999. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  43000. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  43001. }
  43002. // Shadows
  43003. if (scene.shadowsEnabled) {
  43004. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  43005. }
  43006. light._uniformBuffer.update();
  43007. }
  43008. };
  43009. /**
  43010. * Binds the fog information from the scene to the effect for the given mesh.
  43011. * @param scene The scene the lights belongs to
  43012. * @param mesh The mesh we are binding the information to render
  43013. * @param effect The effect we are binding the data to
  43014. */
  43015. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  43016. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  43017. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  43018. effect.setColor3("vFogColor", scene.fogColor);
  43019. }
  43020. };
  43021. /**
  43022. * Binds the bones information from the mesh to the effect.
  43023. * @param mesh The mesh we are binding the information to render
  43024. * @param effect The effect we are binding the data to
  43025. */
  43026. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  43027. if (!effect || !mesh) {
  43028. return;
  43029. }
  43030. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43031. mesh.computeBonesUsingShaders = false;
  43032. }
  43033. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43034. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  43035. if (matrices) {
  43036. effect.setMatrices("mBones", matrices);
  43037. }
  43038. }
  43039. };
  43040. /**
  43041. * Binds the morph targets information from the mesh to the effect.
  43042. * @param abstractMesh The mesh we are binding the information to render
  43043. * @param effect The effect we are binding the data to
  43044. */
  43045. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43046. var manager = abstractMesh.morphTargetManager;
  43047. if (!abstractMesh || !manager) {
  43048. return;
  43049. }
  43050. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43051. };
  43052. /**
  43053. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43054. * @param defines The generated defines used in the effect
  43055. * @param effect The effect we are binding the data to
  43056. * @param scene The scene we are willing to render with logarithmic scale for
  43057. */
  43058. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43059. if (defines["LOGARITHMICDEPTH"]) {
  43060. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43061. }
  43062. };
  43063. /**
  43064. * Binds the clip plane information from the scene to the effect.
  43065. * @param scene The scene the clip plane information are extracted from
  43066. * @param effect The effect we are binding the data to
  43067. */
  43068. MaterialHelper.BindClipPlane = function (effect, scene) {
  43069. if (scene.clipPlane) {
  43070. var clipPlane = scene.clipPlane;
  43071. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43072. }
  43073. };
  43074. return MaterialHelper;
  43075. }());
  43076. BABYLON.MaterialHelper = MaterialHelper;
  43077. })(BABYLON || (BABYLON = {}));
  43078. //# sourceMappingURL=babylon.materialHelper.js.map
  43079. var BABYLON;
  43080. (function (BABYLON) {
  43081. var PushMaterial = /** @class */ (function (_super) {
  43082. __extends(PushMaterial, _super);
  43083. function PushMaterial(name, scene) {
  43084. var _this = _super.call(this, name, scene) || this;
  43085. _this._normalMatrix = new BABYLON.Matrix();
  43086. _this.storeEffectOnSubMeshes = true;
  43087. return _this;
  43088. }
  43089. PushMaterial.prototype.getEffect = function () {
  43090. return this._activeEffect;
  43091. };
  43092. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43093. if (!mesh) {
  43094. return false;
  43095. }
  43096. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43097. return true;
  43098. }
  43099. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43100. };
  43101. /**
  43102. * Binds the given world matrix to the active effect
  43103. *
  43104. * @param world the matrix to bind
  43105. */
  43106. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43107. this._activeEffect.setMatrix("world", world);
  43108. };
  43109. /**
  43110. * Binds the given normal matrix to the active effect
  43111. *
  43112. * @param normalMatrix the matrix to bind
  43113. */
  43114. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43115. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43116. };
  43117. PushMaterial.prototype.bind = function (world, mesh) {
  43118. if (!mesh) {
  43119. return;
  43120. }
  43121. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43122. };
  43123. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43124. if (effect === void 0) { effect = null; }
  43125. _super.prototype._afterBind.call(this, mesh);
  43126. this.getScene()._cachedEffect = effect;
  43127. };
  43128. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43129. if (visibility === void 0) { visibility = 1; }
  43130. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43131. };
  43132. return PushMaterial;
  43133. }(BABYLON.Material));
  43134. BABYLON.PushMaterial = PushMaterial;
  43135. })(BABYLON || (BABYLON = {}));
  43136. //# sourceMappingURL=babylon.pushMaterial.js.map
  43137. var BABYLON;
  43138. (function (BABYLON) {
  43139. /** @hidden */
  43140. var StandardMaterialDefines = /** @class */ (function (_super) {
  43141. __extends(StandardMaterialDefines, _super);
  43142. function StandardMaterialDefines() {
  43143. var _this = _super.call(this) || this;
  43144. _this.MAINUV1 = false;
  43145. _this.MAINUV2 = false;
  43146. _this.DIFFUSE = false;
  43147. _this.DIFFUSEDIRECTUV = 0;
  43148. _this.AMBIENT = false;
  43149. _this.AMBIENTDIRECTUV = 0;
  43150. _this.OPACITY = false;
  43151. _this.OPACITYDIRECTUV = 0;
  43152. _this.OPACITYRGB = false;
  43153. _this.REFLECTION = false;
  43154. _this.EMISSIVE = false;
  43155. _this.EMISSIVEDIRECTUV = 0;
  43156. _this.SPECULAR = false;
  43157. _this.SPECULARDIRECTUV = 0;
  43158. _this.BUMP = false;
  43159. _this.BUMPDIRECTUV = 0;
  43160. _this.PARALLAX = false;
  43161. _this.PARALLAXOCCLUSION = false;
  43162. _this.SPECULAROVERALPHA = false;
  43163. _this.CLIPPLANE = false;
  43164. _this.ALPHATEST = false;
  43165. _this.DEPTHPREPASS = false;
  43166. _this.ALPHAFROMDIFFUSE = false;
  43167. _this.POINTSIZE = false;
  43168. _this.FOG = false;
  43169. _this.SPECULARTERM = false;
  43170. _this.DIFFUSEFRESNEL = false;
  43171. _this.OPACITYFRESNEL = false;
  43172. _this.REFLECTIONFRESNEL = false;
  43173. _this.REFRACTIONFRESNEL = false;
  43174. _this.EMISSIVEFRESNEL = false;
  43175. _this.FRESNEL = false;
  43176. _this.NORMAL = false;
  43177. _this.UV1 = false;
  43178. _this.UV2 = false;
  43179. _this.VERTEXCOLOR = false;
  43180. _this.VERTEXALPHA = false;
  43181. _this.NUM_BONE_INFLUENCERS = 0;
  43182. _this.BonesPerMesh = 0;
  43183. _this.INSTANCES = false;
  43184. _this.GLOSSINESS = false;
  43185. _this.ROUGHNESS = false;
  43186. _this.EMISSIVEASILLUMINATION = false;
  43187. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43188. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43189. _this.LIGHTMAP = false;
  43190. _this.LIGHTMAPDIRECTUV = 0;
  43191. _this.OBJECTSPACE_NORMALMAP = false;
  43192. _this.USELIGHTMAPASSHADOWMAP = false;
  43193. _this.REFLECTIONMAP_3D = false;
  43194. _this.REFLECTIONMAP_SPHERICAL = false;
  43195. _this.REFLECTIONMAP_PLANAR = false;
  43196. _this.REFLECTIONMAP_CUBIC = false;
  43197. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43198. _this.REFLECTIONMAP_PROJECTION = false;
  43199. _this.REFLECTIONMAP_SKYBOX = false;
  43200. _this.REFLECTIONMAP_EXPLICIT = false;
  43201. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43202. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43203. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43204. _this.INVERTCUBICMAP = false;
  43205. _this.LOGARITHMICDEPTH = false;
  43206. _this.REFRACTION = false;
  43207. _this.REFRACTIONMAP_3D = false;
  43208. _this.REFLECTIONOVERALPHA = false;
  43209. _this.TWOSIDEDLIGHTING = false;
  43210. _this.SHADOWFLOAT = false;
  43211. _this.MORPHTARGETS = false;
  43212. _this.MORPHTARGETS_NORMAL = false;
  43213. _this.MORPHTARGETS_TANGENT = false;
  43214. _this.NUM_MORPH_INFLUENCERS = 0;
  43215. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43216. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43217. _this.IMAGEPROCESSING = false;
  43218. _this.VIGNETTE = false;
  43219. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43220. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43221. _this.TONEMAPPING = false;
  43222. _this.CONTRAST = false;
  43223. _this.COLORCURVES = false;
  43224. _this.COLORGRADING = false;
  43225. _this.COLORGRADING3D = false;
  43226. _this.SAMPLER3DGREENDEPTH = false;
  43227. _this.SAMPLER3DBGRMAP = false;
  43228. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43229. /**
  43230. * If the reflection texture on this material is in linear color space
  43231. * @hidden
  43232. */
  43233. _this.IS_REFLECTION_LINEAR = false;
  43234. /**
  43235. * If the refraction texture on this material is in linear color space
  43236. * @hidden
  43237. */
  43238. _this.IS_REFRACTION_LINEAR = false;
  43239. _this.EXPOSURE = false;
  43240. _this.rebuild();
  43241. return _this;
  43242. }
  43243. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43244. var modes = [
  43245. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43246. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43247. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43248. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43249. ];
  43250. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43251. var mode = modes_1[_i];
  43252. this[mode] = (mode === modeToEnable);
  43253. }
  43254. };
  43255. return StandardMaterialDefines;
  43256. }(BABYLON.MaterialDefines));
  43257. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43258. var StandardMaterial = /** @class */ (function (_super) {
  43259. __extends(StandardMaterial, _super);
  43260. function StandardMaterial(name, scene) {
  43261. var _this = _super.call(this, name, scene) || this;
  43262. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43263. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43264. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43265. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43266. _this.specularPower = 64;
  43267. _this._useAlphaFromDiffuseTexture = false;
  43268. _this._useEmissiveAsIllumination = false;
  43269. _this._linkEmissiveWithDiffuse = false;
  43270. _this._useSpecularOverAlpha = false;
  43271. _this._useReflectionOverAlpha = false;
  43272. _this._disableLighting = false;
  43273. _this._useObjectSpaceNormalMap = false;
  43274. _this._useParallax = false;
  43275. _this._useParallaxOcclusion = false;
  43276. _this.parallaxScaleBias = 0.05;
  43277. _this._roughness = 0;
  43278. _this.indexOfRefraction = 0.98;
  43279. _this.invertRefractionY = true;
  43280. /**
  43281. * Defines the alpha limits in alpha test mode
  43282. */
  43283. _this.alphaCutOff = 0.4;
  43284. _this._useLightmapAsShadowmap = false;
  43285. _this._useReflectionFresnelFromSpecular = false;
  43286. _this._useGlossinessFromSpecularMapAlpha = false;
  43287. _this._maxSimultaneousLights = 4;
  43288. /**
  43289. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43290. */
  43291. _this._invertNormalMapX = false;
  43292. /**
  43293. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43294. */
  43295. _this._invertNormalMapY = false;
  43296. /**
  43297. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43298. */
  43299. _this._twoSidedLighting = false;
  43300. _this._renderTargets = new BABYLON.SmartArray(16);
  43301. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43302. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43303. // Setup the default processing configuration to the scene.
  43304. _this._attachImageProcessingConfiguration(null);
  43305. _this.getRenderTargetTextures = function () {
  43306. _this._renderTargets.reset();
  43307. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43308. _this._renderTargets.push(_this._reflectionTexture);
  43309. }
  43310. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43311. _this._renderTargets.push(_this._refractionTexture);
  43312. }
  43313. return _this._renderTargets;
  43314. };
  43315. return _this;
  43316. }
  43317. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43318. /**
  43319. * Gets the image processing configuration used either in this material.
  43320. */
  43321. get: function () {
  43322. return this._imageProcessingConfiguration;
  43323. },
  43324. /**
  43325. * Sets the Default image processing configuration used either in the this material.
  43326. *
  43327. * If sets to null, the scene one is in use.
  43328. */
  43329. set: function (value) {
  43330. this._attachImageProcessingConfiguration(value);
  43331. // Ensure the effect will be rebuilt.
  43332. this._markAllSubMeshesAsTexturesDirty();
  43333. },
  43334. enumerable: true,
  43335. configurable: true
  43336. });
  43337. /**
  43338. * Attaches a new image processing configuration to the Standard Material.
  43339. * @param configuration
  43340. */
  43341. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43342. var _this = this;
  43343. if (configuration === this._imageProcessingConfiguration) {
  43344. return;
  43345. }
  43346. // Detaches observer.
  43347. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43348. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43349. }
  43350. // Pick the scene configuration if needed.
  43351. if (!configuration) {
  43352. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43353. }
  43354. else {
  43355. this._imageProcessingConfiguration = configuration;
  43356. }
  43357. // Attaches observer.
  43358. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43359. _this._markAllSubMeshesAsImageProcessingDirty();
  43360. });
  43361. };
  43362. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43363. /**
  43364. * Gets wether the color curves effect is enabled.
  43365. */
  43366. get: function () {
  43367. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43368. },
  43369. /**
  43370. * Sets wether the color curves effect is enabled.
  43371. */
  43372. set: function (value) {
  43373. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43374. },
  43375. enumerable: true,
  43376. configurable: true
  43377. });
  43378. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43379. /**
  43380. * Gets wether the color grading effect is enabled.
  43381. */
  43382. get: function () {
  43383. return this.imageProcessingConfiguration.colorGradingEnabled;
  43384. },
  43385. /**
  43386. * Gets wether the color grading effect is enabled.
  43387. */
  43388. set: function (value) {
  43389. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43390. },
  43391. enumerable: true,
  43392. configurable: true
  43393. });
  43394. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43395. /**
  43396. * Gets wether tonemapping is enabled or not.
  43397. */
  43398. get: function () {
  43399. return this._imageProcessingConfiguration.toneMappingEnabled;
  43400. },
  43401. /**
  43402. * Sets wether tonemapping is enabled or not
  43403. */
  43404. set: function (value) {
  43405. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43406. },
  43407. enumerable: true,
  43408. configurable: true
  43409. });
  43410. ;
  43411. ;
  43412. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43413. /**
  43414. * The camera exposure used on this material.
  43415. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43416. * This corresponds to a photographic exposure.
  43417. */
  43418. get: function () {
  43419. return this._imageProcessingConfiguration.exposure;
  43420. },
  43421. /**
  43422. * The camera exposure used on this material.
  43423. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43424. * This corresponds to a photographic exposure.
  43425. */
  43426. set: function (value) {
  43427. this._imageProcessingConfiguration.exposure = value;
  43428. },
  43429. enumerable: true,
  43430. configurable: true
  43431. });
  43432. ;
  43433. ;
  43434. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43435. /**
  43436. * Gets The camera contrast used on this material.
  43437. */
  43438. get: function () {
  43439. return this._imageProcessingConfiguration.contrast;
  43440. },
  43441. /**
  43442. * Sets The camera contrast used on this material.
  43443. */
  43444. set: function (value) {
  43445. this._imageProcessingConfiguration.contrast = value;
  43446. },
  43447. enumerable: true,
  43448. configurable: true
  43449. });
  43450. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43451. /**
  43452. * Gets the Color Grading 2D Lookup Texture.
  43453. */
  43454. get: function () {
  43455. return this._imageProcessingConfiguration.colorGradingTexture;
  43456. },
  43457. /**
  43458. * Sets the Color Grading 2D Lookup Texture.
  43459. */
  43460. set: function (value) {
  43461. this._imageProcessingConfiguration.colorGradingTexture = value;
  43462. },
  43463. enumerable: true,
  43464. configurable: true
  43465. });
  43466. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43467. /**
  43468. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43469. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43470. * 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;
  43471. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43472. */
  43473. get: function () {
  43474. return this._imageProcessingConfiguration.colorCurves;
  43475. },
  43476. /**
  43477. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43478. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43479. * 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;
  43480. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43481. */
  43482. set: function (value) {
  43483. this._imageProcessingConfiguration.colorCurves = value;
  43484. },
  43485. enumerable: true,
  43486. configurable: true
  43487. });
  43488. StandardMaterial.prototype.getClassName = function () {
  43489. return "StandardMaterial";
  43490. };
  43491. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43492. get: function () {
  43493. return this._useLogarithmicDepth;
  43494. },
  43495. set: function (value) {
  43496. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43497. this._markAllSubMeshesAsMiscDirty();
  43498. },
  43499. enumerable: true,
  43500. configurable: true
  43501. });
  43502. StandardMaterial.prototype.needAlphaBlending = function () {
  43503. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43504. };
  43505. StandardMaterial.prototype.needAlphaTesting = function () {
  43506. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43507. };
  43508. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43509. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43510. };
  43511. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43512. return this._diffuseTexture;
  43513. };
  43514. /**
  43515. * Child classes can use it to update shaders
  43516. */
  43517. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43518. if (useInstances === void 0) { useInstances = false; }
  43519. if (subMesh.effect && this.isFrozen) {
  43520. if (this._wasPreviouslyReady && subMesh.effect) {
  43521. return true;
  43522. }
  43523. }
  43524. if (!subMesh._materialDefines) {
  43525. subMesh._materialDefines = new StandardMaterialDefines();
  43526. }
  43527. var scene = this.getScene();
  43528. var defines = subMesh._materialDefines;
  43529. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43530. if (defines._renderId === scene.getRenderId()) {
  43531. return true;
  43532. }
  43533. }
  43534. var engine = scene.getEngine();
  43535. // Lights
  43536. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43537. // Textures
  43538. if (defines._areTexturesDirty) {
  43539. defines._needUVs = false;
  43540. defines.MAINUV1 = false;
  43541. defines.MAINUV2 = false;
  43542. if (scene.texturesEnabled) {
  43543. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43544. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43545. return false;
  43546. }
  43547. else {
  43548. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43549. }
  43550. }
  43551. else {
  43552. defines.DIFFUSE = false;
  43553. }
  43554. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43555. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43556. return false;
  43557. }
  43558. else {
  43559. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43560. }
  43561. }
  43562. else {
  43563. defines.AMBIENT = false;
  43564. }
  43565. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43566. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43567. return false;
  43568. }
  43569. else {
  43570. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43571. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43572. }
  43573. }
  43574. else {
  43575. defines.OPACITY = false;
  43576. }
  43577. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43578. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43579. return false;
  43580. }
  43581. else {
  43582. defines._needNormals = true;
  43583. defines.REFLECTION = true;
  43584. defines.ROUGHNESS = (this._roughness > 0);
  43585. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43586. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43587. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43588. switch (this._reflectionTexture.coordinatesMode) {
  43589. case BABYLON.Texture.EXPLICIT_MODE:
  43590. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43591. break;
  43592. case BABYLON.Texture.PLANAR_MODE:
  43593. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43594. break;
  43595. case BABYLON.Texture.PROJECTION_MODE:
  43596. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43597. break;
  43598. case BABYLON.Texture.SKYBOX_MODE:
  43599. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43600. break;
  43601. case BABYLON.Texture.SPHERICAL_MODE:
  43602. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43603. break;
  43604. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43605. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43606. break;
  43607. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43608. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43609. break;
  43610. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43611. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43612. break;
  43613. case BABYLON.Texture.CUBIC_MODE:
  43614. case BABYLON.Texture.INVCUBIC_MODE:
  43615. default:
  43616. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43617. break;
  43618. }
  43619. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43620. }
  43621. }
  43622. else {
  43623. defines.REFLECTION = false;
  43624. }
  43625. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43626. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43627. return false;
  43628. }
  43629. else {
  43630. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43631. }
  43632. }
  43633. else {
  43634. defines.EMISSIVE = false;
  43635. }
  43636. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43637. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43638. return false;
  43639. }
  43640. else {
  43641. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43642. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43643. }
  43644. }
  43645. else {
  43646. defines.LIGHTMAP = false;
  43647. }
  43648. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43649. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43650. return false;
  43651. }
  43652. else {
  43653. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43654. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43655. }
  43656. }
  43657. else {
  43658. defines.SPECULAR = false;
  43659. }
  43660. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43661. // Bump texure can not be not blocking.
  43662. if (!this._bumpTexture.isReady()) {
  43663. return false;
  43664. }
  43665. else {
  43666. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43667. defines.PARALLAX = this._useParallax;
  43668. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43669. }
  43670. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43671. }
  43672. else {
  43673. defines.BUMP = false;
  43674. }
  43675. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43676. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43677. return false;
  43678. }
  43679. else {
  43680. defines._needUVs = true;
  43681. defines.REFRACTION = true;
  43682. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43683. }
  43684. }
  43685. else {
  43686. defines.REFRACTION = false;
  43687. }
  43688. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43689. }
  43690. else {
  43691. defines.DIFFUSE = false;
  43692. defines.AMBIENT = false;
  43693. defines.OPACITY = false;
  43694. defines.REFLECTION = false;
  43695. defines.EMISSIVE = false;
  43696. defines.LIGHTMAP = false;
  43697. defines.BUMP = false;
  43698. defines.REFRACTION = false;
  43699. }
  43700. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43701. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43702. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43703. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43704. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43705. }
  43706. if (defines._areImageProcessingDirty) {
  43707. if (!this._imageProcessingConfiguration.isReady()) {
  43708. return false;
  43709. }
  43710. this._imageProcessingConfiguration.prepareDefines(defines);
  43711. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43712. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43713. }
  43714. if (defines._areFresnelDirty) {
  43715. if (StandardMaterial.FresnelEnabled) {
  43716. // Fresnel
  43717. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43718. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43719. this._reflectionFresnelParameters) {
  43720. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43721. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43722. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43723. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43724. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43725. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43726. defines._needNormals = true;
  43727. defines.FRESNEL = true;
  43728. }
  43729. }
  43730. else {
  43731. defines.FRESNEL = false;
  43732. }
  43733. }
  43734. // Misc.
  43735. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43736. // Attribs
  43737. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43738. // Values that need to be evaluated on every frame
  43739. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43740. // Get correct effect
  43741. if (defines.isDirty) {
  43742. defines.markAsProcessed();
  43743. scene.resetCachedMaterial();
  43744. // Fallbacks
  43745. var fallbacks = new BABYLON.EffectFallbacks();
  43746. if (defines.REFLECTION) {
  43747. fallbacks.addFallback(0, "REFLECTION");
  43748. }
  43749. if (defines.SPECULAR) {
  43750. fallbacks.addFallback(0, "SPECULAR");
  43751. }
  43752. if (defines.BUMP) {
  43753. fallbacks.addFallback(0, "BUMP");
  43754. }
  43755. if (defines.PARALLAX) {
  43756. fallbacks.addFallback(1, "PARALLAX");
  43757. }
  43758. if (defines.PARALLAXOCCLUSION) {
  43759. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43760. }
  43761. if (defines.SPECULAROVERALPHA) {
  43762. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43763. }
  43764. if (defines.FOG) {
  43765. fallbacks.addFallback(1, "FOG");
  43766. }
  43767. if (defines.POINTSIZE) {
  43768. fallbacks.addFallback(0, "POINTSIZE");
  43769. }
  43770. if (defines.LOGARITHMICDEPTH) {
  43771. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43772. }
  43773. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43774. if (defines.SPECULARTERM) {
  43775. fallbacks.addFallback(0, "SPECULARTERM");
  43776. }
  43777. if (defines.DIFFUSEFRESNEL) {
  43778. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43779. }
  43780. if (defines.OPACITYFRESNEL) {
  43781. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43782. }
  43783. if (defines.REFLECTIONFRESNEL) {
  43784. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43785. }
  43786. if (defines.EMISSIVEFRESNEL) {
  43787. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43788. }
  43789. if (defines.FRESNEL) {
  43790. fallbacks.addFallback(4, "FRESNEL");
  43791. }
  43792. //Attributes
  43793. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43794. if (defines.NORMAL) {
  43795. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43796. }
  43797. if (defines.UV1) {
  43798. attribs.push(BABYLON.VertexBuffer.UVKind);
  43799. }
  43800. if (defines.UV2) {
  43801. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43802. }
  43803. if (defines.VERTEXCOLOR) {
  43804. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43805. }
  43806. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43807. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43808. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43809. var shaderName = "default";
  43810. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43811. "vFogInfos", "vFogColor", "pointSize",
  43812. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43813. "mBones",
  43814. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43815. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43816. "vReflectionPosition", "vReflectionSize",
  43817. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43818. ];
  43819. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43820. var uniformBuffers = ["Material", "Scene"];
  43821. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43822. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43823. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43824. uniformsNames: uniforms,
  43825. uniformBuffersNames: uniformBuffers,
  43826. samplers: samplers,
  43827. defines: defines,
  43828. maxSimultaneousLights: this._maxSimultaneousLights
  43829. });
  43830. if (this.customShaderNameResolve) {
  43831. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43832. }
  43833. var join = defines.toString();
  43834. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43835. attributes: attribs,
  43836. uniformsNames: uniforms,
  43837. uniformBuffersNames: uniformBuffers,
  43838. samplers: samplers,
  43839. defines: join,
  43840. fallbacks: fallbacks,
  43841. onCompiled: this.onCompiled,
  43842. onError: this.onError,
  43843. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43844. }, engine), defines);
  43845. this.buildUniformLayout();
  43846. }
  43847. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43848. return false;
  43849. }
  43850. defines._renderId = scene.getRenderId();
  43851. this._wasPreviouslyReady = true;
  43852. return true;
  43853. };
  43854. StandardMaterial.prototype.buildUniformLayout = function () {
  43855. // Order is important !
  43856. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43857. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43858. this._uniformBuffer.addUniform("opacityParts", 4);
  43859. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43860. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43861. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43862. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43863. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43864. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43865. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43866. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43867. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43868. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43869. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43870. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43871. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43872. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43873. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43874. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43875. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43876. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43877. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43878. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43879. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43880. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43881. this._uniformBuffer.addUniform("specularMatrix", 16);
  43882. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43883. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43884. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43885. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43886. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43887. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43888. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43889. this._uniformBuffer.addUniform("pointSize", 1);
  43890. this._uniformBuffer.create();
  43891. };
  43892. StandardMaterial.prototype.unbind = function () {
  43893. if (this._activeEffect) {
  43894. var needFlag = false;
  43895. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43896. this._activeEffect.setTexture("reflection2DSampler", null);
  43897. needFlag = true;
  43898. }
  43899. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43900. this._activeEffect.setTexture("refraction2DSampler", null);
  43901. needFlag = true;
  43902. }
  43903. if (needFlag) {
  43904. this._markAllSubMeshesAsTexturesDirty();
  43905. }
  43906. }
  43907. _super.prototype.unbind.call(this);
  43908. };
  43909. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43910. var scene = this.getScene();
  43911. var defines = subMesh._materialDefines;
  43912. if (!defines) {
  43913. return;
  43914. }
  43915. var effect = subMesh.effect;
  43916. if (!effect) {
  43917. return;
  43918. }
  43919. this._activeEffect = effect;
  43920. // Matrices
  43921. this.bindOnlyWorldMatrix(world);
  43922. // Normal Matrix
  43923. if (defines.OBJECTSPACE_NORMALMAP) {
  43924. world.toNormalMatrix(this._normalMatrix);
  43925. this.bindOnlyNormalMatrix(this._normalMatrix);
  43926. }
  43927. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43928. // Bones
  43929. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43930. if (mustRebind) {
  43931. this._uniformBuffer.bindToEffect(effect, "Material");
  43932. this.bindViewProjection(effect);
  43933. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43934. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43935. // Fresnel
  43936. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43937. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43938. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43939. }
  43940. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43941. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43942. }
  43943. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43944. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43945. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43946. }
  43947. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43948. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43949. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43950. }
  43951. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43952. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43953. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43954. }
  43955. }
  43956. // Textures
  43957. if (scene.texturesEnabled) {
  43958. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43959. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43960. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43961. if (this._diffuseTexture.hasAlpha) {
  43962. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43963. }
  43964. }
  43965. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43966. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43967. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43968. }
  43969. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43970. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43971. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43972. }
  43973. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43974. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43975. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43976. if (this._reflectionTexture.boundingBoxSize) {
  43977. var cubeTexture = this._reflectionTexture;
  43978. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43979. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43980. }
  43981. }
  43982. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43983. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43984. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43985. }
  43986. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43987. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43988. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43989. }
  43990. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43991. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43992. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43993. }
  43994. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43995. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43996. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43997. if (scene._mirroredCameraPosition) {
  43998. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43999. }
  44000. else {
  44001. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44002. }
  44003. }
  44004. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44005. var depth = 1.0;
  44006. if (!this._refractionTexture.isCube) {
  44007. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  44008. if (this._refractionTexture.depth) {
  44009. depth = this._refractionTexture.depth;
  44010. }
  44011. }
  44012. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44013. }
  44014. }
  44015. // Point size
  44016. if (this.pointsCloud) {
  44017. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44018. }
  44019. if (defines.SPECULARTERM) {
  44020. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  44021. }
  44022. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  44023. // Diffuse
  44024. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  44025. }
  44026. // Textures
  44027. if (scene.texturesEnabled) {
  44028. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44029. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44030. }
  44031. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44032. effect.setTexture("ambientSampler", this._ambientTexture);
  44033. }
  44034. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44035. effect.setTexture("opacitySampler", this._opacityTexture);
  44036. }
  44037. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44038. if (this._reflectionTexture.isCube) {
  44039. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44040. }
  44041. else {
  44042. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44043. }
  44044. }
  44045. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44046. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44047. }
  44048. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44049. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44050. }
  44051. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44052. effect.setTexture("specularSampler", this._specularTexture);
  44053. }
  44054. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44055. effect.setTexture("bumpSampler", this._bumpTexture);
  44056. }
  44057. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44058. var depth = 1.0;
  44059. if (this._refractionTexture.isCube) {
  44060. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44061. }
  44062. else {
  44063. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44064. }
  44065. }
  44066. }
  44067. // Clip plane
  44068. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44069. // Colors
  44070. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44071. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44072. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44073. }
  44074. if (mustRebind || !this.isFrozen) {
  44075. // Lights
  44076. if (scene.lightsEnabled && !this._disableLighting) {
  44077. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44078. }
  44079. // View
  44080. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44081. this.bindView(effect);
  44082. }
  44083. // Fog
  44084. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44085. // Morph targets
  44086. if (defines.NUM_MORPH_INFLUENCERS) {
  44087. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44088. }
  44089. // Log. depth
  44090. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44091. // image processing
  44092. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  44093. this._imageProcessingConfiguration.bind(this._activeEffect);
  44094. }
  44095. }
  44096. this._uniformBuffer.update();
  44097. this._afterBind(mesh, this._activeEffect);
  44098. };
  44099. StandardMaterial.prototype.getAnimatables = function () {
  44100. var results = [];
  44101. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44102. results.push(this._diffuseTexture);
  44103. }
  44104. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44105. results.push(this._ambientTexture);
  44106. }
  44107. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44108. results.push(this._opacityTexture);
  44109. }
  44110. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44111. results.push(this._reflectionTexture);
  44112. }
  44113. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44114. results.push(this._emissiveTexture);
  44115. }
  44116. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44117. results.push(this._specularTexture);
  44118. }
  44119. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44120. results.push(this._bumpTexture);
  44121. }
  44122. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44123. results.push(this._lightmapTexture);
  44124. }
  44125. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44126. results.push(this._refractionTexture);
  44127. }
  44128. return results;
  44129. };
  44130. StandardMaterial.prototype.getActiveTextures = function () {
  44131. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44132. if (this._diffuseTexture) {
  44133. activeTextures.push(this._diffuseTexture);
  44134. }
  44135. if (this._ambientTexture) {
  44136. activeTextures.push(this._ambientTexture);
  44137. }
  44138. if (this._opacityTexture) {
  44139. activeTextures.push(this._opacityTexture);
  44140. }
  44141. if (this._reflectionTexture) {
  44142. activeTextures.push(this._reflectionTexture);
  44143. }
  44144. if (this._emissiveTexture) {
  44145. activeTextures.push(this._emissiveTexture);
  44146. }
  44147. if (this._specularTexture) {
  44148. activeTextures.push(this._specularTexture);
  44149. }
  44150. if (this._bumpTexture) {
  44151. activeTextures.push(this._bumpTexture);
  44152. }
  44153. if (this._lightmapTexture) {
  44154. activeTextures.push(this._lightmapTexture);
  44155. }
  44156. if (this._refractionTexture) {
  44157. activeTextures.push(this._refractionTexture);
  44158. }
  44159. return activeTextures;
  44160. };
  44161. StandardMaterial.prototype.hasTexture = function (texture) {
  44162. if (_super.prototype.hasTexture.call(this, texture)) {
  44163. return true;
  44164. }
  44165. if (this._diffuseTexture === texture) {
  44166. return true;
  44167. }
  44168. if (this._ambientTexture === texture) {
  44169. return true;
  44170. }
  44171. if (this._opacityTexture === texture) {
  44172. return true;
  44173. }
  44174. if (this._reflectionTexture === texture) {
  44175. return true;
  44176. }
  44177. if (this._emissiveTexture === texture) {
  44178. return true;
  44179. }
  44180. if (this._specularTexture === texture) {
  44181. return true;
  44182. }
  44183. if (this._bumpTexture === texture) {
  44184. return true;
  44185. }
  44186. if (this._lightmapTexture === texture) {
  44187. return true;
  44188. }
  44189. if (this._refractionTexture === texture) {
  44190. return true;
  44191. }
  44192. return false;
  44193. };
  44194. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44195. if (forceDisposeTextures) {
  44196. if (this._diffuseTexture) {
  44197. this._diffuseTexture.dispose();
  44198. }
  44199. if (this._ambientTexture) {
  44200. this._ambientTexture.dispose();
  44201. }
  44202. if (this._opacityTexture) {
  44203. this._opacityTexture.dispose();
  44204. }
  44205. if (this._reflectionTexture) {
  44206. this._reflectionTexture.dispose();
  44207. }
  44208. if (this._emissiveTexture) {
  44209. this._emissiveTexture.dispose();
  44210. }
  44211. if (this._specularTexture) {
  44212. this._specularTexture.dispose();
  44213. }
  44214. if (this._bumpTexture) {
  44215. this._bumpTexture.dispose();
  44216. }
  44217. if (this._lightmapTexture) {
  44218. this._lightmapTexture.dispose();
  44219. }
  44220. if (this._refractionTexture) {
  44221. this._refractionTexture.dispose();
  44222. }
  44223. }
  44224. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44225. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44226. }
  44227. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44228. };
  44229. StandardMaterial.prototype.clone = function (name) {
  44230. var _this = this;
  44231. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44232. result.name = name;
  44233. result.id = name;
  44234. return result;
  44235. };
  44236. StandardMaterial.prototype.serialize = function () {
  44237. return BABYLON.SerializationHelper.Serialize(this);
  44238. };
  44239. // Statics
  44240. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44241. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44242. };
  44243. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44244. get: function () {
  44245. return StandardMaterial._DiffuseTextureEnabled;
  44246. },
  44247. set: function (value) {
  44248. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44249. return;
  44250. }
  44251. StandardMaterial._DiffuseTextureEnabled = value;
  44252. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44253. },
  44254. enumerable: true,
  44255. configurable: true
  44256. });
  44257. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44258. get: function () {
  44259. return StandardMaterial._AmbientTextureEnabled;
  44260. },
  44261. set: function (value) {
  44262. if (StandardMaterial._AmbientTextureEnabled === value) {
  44263. return;
  44264. }
  44265. StandardMaterial._AmbientTextureEnabled = value;
  44266. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44267. },
  44268. enumerable: true,
  44269. configurable: true
  44270. });
  44271. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44272. get: function () {
  44273. return StandardMaterial._OpacityTextureEnabled;
  44274. },
  44275. set: function (value) {
  44276. if (StandardMaterial._OpacityTextureEnabled === value) {
  44277. return;
  44278. }
  44279. StandardMaterial._OpacityTextureEnabled = value;
  44280. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44281. },
  44282. enumerable: true,
  44283. configurable: true
  44284. });
  44285. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44286. get: function () {
  44287. return StandardMaterial._ReflectionTextureEnabled;
  44288. },
  44289. set: function (value) {
  44290. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44291. return;
  44292. }
  44293. StandardMaterial._ReflectionTextureEnabled = value;
  44294. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44295. },
  44296. enumerable: true,
  44297. configurable: true
  44298. });
  44299. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44300. get: function () {
  44301. return StandardMaterial._EmissiveTextureEnabled;
  44302. },
  44303. set: function (value) {
  44304. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44305. return;
  44306. }
  44307. StandardMaterial._EmissiveTextureEnabled = value;
  44308. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44309. },
  44310. enumerable: true,
  44311. configurable: true
  44312. });
  44313. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44314. get: function () {
  44315. return StandardMaterial._SpecularTextureEnabled;
  44316. },
  44317. set: function (value) {
  44318. if (StandardMaterial._SpecularTextureEnabled === value) {
  44319. return;
  44320. }
  44321. StandardMaterial._SpecularTextureEnabled = value;
  44322. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44323. },
  44324. enumerable: true,
  44325. configurable: true
  44326. });
  44327. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44328. get: function () {
  44329. return StandardMaterial._BumpTextureEnabled;
  44330. },
  44331. set: function (value) {
  44332. if (StandardMaterial._BumpTextureEnabled === value) {
  44333. return;
  44334. }
  44335. StandardMaterial._BumpTextureEnabled = value;
  44336. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44337. },
  44338. enumerable: true,
  44339. configurable: true
  44340. });
  44341. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44342. get: function () {
  44343. return StandardMaterial._LightmapTextureEnabled;
  44344. },
  44345. set: function (value) {
  44346. if (StandardMaterial._LightmapTextureEnabled === value) {
  44347. return;
  44348. }
  44349. StandardMaterial._LightmapTextureEnabled = value;
  44350. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44351. },
  44352. enumerable: true,
  44353. configurable: true
  44354. });
  44355. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44356. get: function () {
  44357. return StandardMaterial._RefractionTextureEnabled;
  44358. },
  44359. set: function (value) {
  44360. if (StandardMaterial._RefractionTextureEnabled === value) {
  44361. return;
  44362. }
  44363. StandardMaterial._RefractionTextureEnabled = value;
  44364. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44365. },
  44366. enumerable: true,
  44367. configurable: true
  44368. });
  44369. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44370. get: function () {
  44371. return StandardMaterial._ColorGradingTextureEnabled;
  44372. },
  44373. set: function (value) {
  44374. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44375. return;
  44376. }
  44377. StandardMaterial._ColorGradingTextureEnabled = value;
  44378. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44379. },
  44380. enumerable: true,
  44381. configurable: true
  44382. });
  44383. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44384. get: function () {
  44385. return StandardMaterial._FresnelEnabled;
  44386. },
  44387. set: function (value) {
  44388. if (StandardMaterial._FresnelEnabled === value) {
  44389. return;
  44390. }
  44391. StandardMaterial._FresnelEnabled = value;
  44392. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44393. },
  44394. enumerable: true,
  44395. configurable: true
  44396. });
  44397. // Flags used to enable or disable a type of texture for all Standard Materials
  44398. StandardMaterial._DiffuseTextureEnabled = true;
  44399. StandardMaterial._AmbientTextureEnabled = true;
  44400. StandardMaterial._OpacityTextureEnabled = true;
  44401. StandardMaterial._ReflectionTextureEnabled = true;
  44402. StandardMaterial._EmissiveTextureEnabled = true;
  44403. StandardMaterial._SpecularTextureEnabled = true;
  44404. StandardMaterial._BumpTextureEnabled = true;
  44405. StandardMaterial._LightmapTextureEnabled = true;
  44406. StandardMaterial._RefractionTextureEnabled = true;
  44407. StandardMaterial._ColorGradingTextureEnabled = true;
  44408. StandardMaterial._FresnelEnabled = true;
  44409. __decorate([
  44410. BABYLON.serializeAsTexture("diffuseTexture")
  44411. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44412. __decorate([
  44413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44414. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44415. __decorate([
  44416. BABYLON.serializeAsTexture("ambientTexture")
  44417. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44418. __decorate([
  44419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44420. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44421. __decorate([
  44422. BABYLON.serializeAsTexture("opacityTexture")
  44423. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44424. __decorate([
  44425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44426. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44427. __decorate([
  44428. BABYLON.serializeAsTexture("reflectionTexture")
  44429. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44430. __decorate([
  44431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44432. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44433. __decorate([
  44434. BABYLON.serializeAsTexture("emissiveTexture")
  44435. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44436. __decorate([
  44437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44438. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44439. __decorate([
  44440. BABYLON.serializeAsTexture("specularTexture")
  44441. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44442. __decorate([
  44443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44444. ], StandardMaterial.prototype, "specularTexture", void 0);
  44445. __decorate([
  44446. BABYLON.serializeAsTexture("bumpTexture")
  44447. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44448. __decorate([
  44449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44450. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44451. __decorate([
  44452. BABYLON.serializeAsTexture("lightmapTexture")
  44453. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44454. __decorate([
  44455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44456. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44457. __decorate([
  44458. BABYLON.serializeAsTexture("refractionTexture")
  44459. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44460. __decorate([
  44461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44462. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44463. __decorate([
  44464. BABYLON.serializeAsColor3("ambient")
  44465. ], StandardMaterial.prototype, "ambientColor", void 0);
  44466. __decorate([
  44467. BABYLON.serializeAsColor3("diffuse")
  44468. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44469. __decorate([
  44470. BABYLON.serializeAsColor3("specular")
  44471. ], StandardMaterial.prototype, "specularColor", void 0);
  44472. __decorate([
  44473. BABYLON.serializeAsColor3("emissive")
  44474. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44475. __decorate([
  44476. BABYLON.serialize()
  44477. ], StandardMaterial.prototype, "specularPower", void 0);
  44478. __decorate([
  44479. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44480. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44481. __decorate([
  44482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44483. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44484. __decorate([
  44485. BABYLON.serialize("useEmissiveAsIllumination")
  44486. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44487. __decorate([
  44488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44489. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44490. __decorate([
  44491. BABYLON.serialize("linkEmissiveWithDiffuse")
  44492. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44493. __decorate([
  44494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44495. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44496. __decorate([
  44497. BABYLON.serialize("useSpecularOverAlpha")
  44498. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44499. __decorate([
  44500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44501. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44502. __decorate([
  44503. BABYLON.serialize("useReflectionOverAlpha")
  44504. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44505. __decorate([
  44506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44507. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44508. __decorate([
  44509. BABYLON.serialize("disableLighting")
  44510. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44511. __decorate([
  44512. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44513. ], StandardMaterial.prototype, "disableLighting", void 0);
  44514. __decorate([
  44515. BABYLON.serialize("useObjectSpaceNormalMap")
  44516. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44517. __decorate([
  44518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44519. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44520. __decorate([
  44521. BABYLON.serialize("useParallax")
  44522. ], StandardMaterial.prototype, "_useParallax", void 0);
  44523. __decorate([
  44524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44525. ], StandardMaterial.prototype, "useParallax", void 0);
  44526. __decorate([
  44527. BABYLON.serialize("useParallaxOcclusion")
  44528. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44529. __decorate([
  44530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44531. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44532. __decorate([
  44533. BABYLON.serialize()
  44534. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44535. __decorate([
  44536. BABYLON.serialize("roughness")
  44537. ], StandardMaterial.prototype, "_roughness", void 0);
  44538. __decorate([
  44539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44540. ], StandardMaterial.prototype, "roughness", void 0);
  44541. __decorate([
  44542. BABYLON.serialize()
  44543. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44544. __decorate([
  44545. BABYLON.serialize()
  44546. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44547. __decorate([
  44548. BABYLON.serialize()
  44549. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44550. __decorate([
  44551. BABYLON.serialize("useLightmapAsShadowmap")
  44552. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44553. __decorate([
  44554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44555. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44556. __decorate([
  44557. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44558. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44559. __decorate([
  44560. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44561. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44562. __decorate([
  44563. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44564. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44565. __decorate([
  44566. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44567. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44568. __decorate([
  44569. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44570. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44571. __decorate([
  44572. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44573. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44574. __decorate([
  44575. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44576. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44577. __decorate([
  44578. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44579. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44580. __decorate([
  44581. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44582. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44583. __decorate([
  44584. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44585. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44586. __decorate([
  44587. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44588. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44589. __decorate([
  44590. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44591. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44592. __decorate([
  44593. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44594. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44595. __decorate([
  44596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44597. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44598. __decorate([
  44599. BABYLON.serialize("maxSimultaneousLights")
  44600. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44601. __decorate([
  44602. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44603. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44604. __decorate([
  44605. BABYLON.serialize("invertNormalMapX")
  44606. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44607. __decorate([
  44608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44609. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44610. __decorate([
  44611. BABYLON.serialize("invertNormalMapY")
  44612. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44613. __decorate([
  44614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44615. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44616. __decorate([
  44617. BABYLON.serialize("twoSidedLighting")
  44618. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44619. __decorate([
  44620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44621. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44622. __decorate([
  44623. BABYLON.serialize()
  44624. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44625. return StandardMaterial;
  44626. }(BABYLON.PushMaterial));
  44627. BABYLON.StandardMaterial = StandardMaterial;
  44628. })(BABYLON || (BABYLON = {}));
  44629. //# sourceMappingURL=babylon.standardMaterial.js.map
  44630. var BABYLON;
  44631. (function (BABYLON) {
  44632. /**
  44633. * Manages the defines for the PBR Material.
  44634. * @hiddenChildren
  44635. */
  44636. var PBRMaterialDefines = /** @class */ (function (_super) {
  44637. __extends(PBRMaterialDefines, _super);
  44638. /**
  44639. * Initializes the PBR Material defines.
  44640. */
  44641. function PBRMaterialDefines() {
  44642. var _this = _super.call(this) || this;
  44643. _this.PBR = true;
  44644. _this.MAINUV1 = false;
  44645. _this.MAINUV2 = false;
  44646. _this.UV1 = false;
  44647. _this.UV2 = false;
  44648. _this.ALBEDO = false;
  44649. _this.ALBEDODIRECTUV = 0;
  44650. _this.VERTEXCOLOR = false;
  44651. _this.AMBIENT = false;
  44652. _this.AMBIENTDIRECTUV = 0;
  44653. _this.AMBIENTINGRAYSCALE = false;
  44654. _this.OPACITY = false;
  44655. _this.VERTEXALPHA = false;
  44656. _this.OPACITYDIRECTUV = 0;
  44657. _this.OPACITYRGB = false;
  44658. _this.ALPHATEST = false;
  44659. _this.DEPTHPREPASS = false;
  44660. _this.ALPHABLEND = false;
  44661. _this.ALPHAFROMALBEDO = false;
  44662. _this.ALPHATESTVALUE = "0.5";
  44663. _this.SPECULAROVERALPHA = false;
  44664. _this.RADIANCEOVERALPHA = false;
  44665. _this.ALPHAFRESNEL = false;
  44666. _this.LINEARALPHAFRESNEL = false;
  44667. _this.PREMULTIPLYALPHA = false;
  44668. _this.EMISSIVE = false;
  44669. _this.EMISSIVEDIRECTUV = 0;
  44670. _this.REFLECTIVITY = false;
  44671. _this.REFLECTIVITYDIRECTUV = 0;
  44672. _this.SPECULARTERM = false;
  44673. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44674. _this.MICROSURFACEAUTOMATIC = false;
  44675. _this.LODBASEDMICROSFURACE = false;
  44676. _this.MICROSURFACEMAP = false;
  44677. _this.MICROSURFACEMAPDIRECTUV = 0;
  44678. _this.METALLICWORKFLOW = false;
  44679. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44680. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44681. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44682. _this.AOSTOREINMETALMAPRED = false;
  44683. _this.ENVIRONMENTBRDF = false;
  44684. _this.NORMAL = false;
  44685. _this.TANGENT = false;
  44686. _this.BUMP = false;
  44687. _this.BUMPDIRECTUV = 0;
  44688. _this.OBJECTSPACE_NORMALMAP = false;
  44689. _this.PARALLAX = false;
  44690. _this.PARALLAXOCCLUSION = false;
  44691. _this.NORMALXYSCALE = true;
  44692. _this.LIGHTMAP = false;
  44693. _this.LIGHTMAPDIRECTUV = 0;
  44694. _this.USELIGHTMAPASSHADOWMAP = false;
  44695. _this.GAMMALIGHTMAP = false;
  44696. _this.REFLECTION = false;
  44697. _this.REFLECTIONMAP_3D = false;
  44698. _this.REFLECTIONMAP_SPHERICAL = false;
  44699. _this.REFLECTIONMAP_PLANAR = false;
  44700. _this.REFLECTIONMAP_CUBIC = false;
  44701. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44702. _this.REFLECTIONMAP_PROJECTION = false;
  44703. _this.REFLECTIONMAP_SKYBOX = false;
  44704. _this.REFLECTIONMAP_EXPLICIT = false;
  44705. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44706. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44707. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44708. _this.INVERTCUBICMAP = false;
  44709. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44710. _this.USESPHERICALINVERTEX = false;
  44711. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44712. _this.LODINREFLECTIONALPHA = false;
  44713. _this.GAMMAREFLECTION = false;
  44714. _this.RGBDREFLECTION = false;
  44715. _this.RADIANCEOCCLUSION = false;
  44716. _this.HORIZONOCCLUSION = false;
  44717. _this.REFRACTION = false;
  44718. _this.REFRACTIONMAP_3D = false;
  44719. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44720. _this.LODINREFRACTIONALPHA = false;
  44721. _this.GAMMAREFRACTION = false;
  44722. _this.RGBDREFRACTION = false;
  44723. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44724. _this.INSTANCES = false;
  44725. _this.NUM_BONE_INFLUENCERS = 0;
  44726. _this.BonesPerMesh = 0;
  44727. _this.NONUNIFORMSCALING = false;
  44728. _this.MORPHTARGETS = false;
  44729. _this.MORPHTARGETS_NORMAL = false;
  44730. _this.MORPHTARGETS_TANGENT = false;
  44731. _this.NUM_MORPH_INFLUENCERS = 0;
  44732. _this.IMAGEPROCESSING = false;
  44733. _this.VIGNETTE = false;
  44734. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44735. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44736. _this.TONEMAPPING = false;
  44737. _this.CONTRAST = false;
  44738. _this.COLORCURVES = false;
  44739. _this.COLORGRADING = false;
  44740. _this.COLORGRADING3D = false;
  44741. _this.SAMPLER3DGREENDEPTH = false;
  44742. _this.SAMPLER3DBGRMAP = false;
  44743. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44744. _this.EXPOSURE = false;
  44745. _this.USEPHYSICALLIGHTFALLOFF = false;
  44746. _this.TWOSIDEDLIGHTING = false;
  44747. _this.SHADOWFLOAT = false;
  44748. _this.CLIPPLANE = false;
  44749. _this.POINTSIZE = false;
  44750. _this.FOG = false;
  44751. _this.LOGARITHMICDEPTH = false;
  44752. _this.FORCENORMALFORWARD = false;
  44753. _this.SPECULARAA = false;
  44754. _this.UNLIT = false;
  44755. _this.rebuild();
  44756. return _this;
  44757. }
  44758. /**
  44759. * Resets the PBR Material defines.
  44760. */
  44761. PBRMaterialDefines.prototype.reset = function () {
  44762. _super.prototype.reset.call(this);
  44763. this.ALPHATESTVALUE = "0.5";
  44764. this.PBR = true;
  44765. };
  44766. return PBRMaterialDefines;
  44767. }(BABYLON.MaterialDefines));
  44768. /**
  44769. * The Physically based material base class of BJS.
  44770. *
  44771. * This offers the main features of a standard PBR material.
  44772. * For more information, please refer to the documentation :
  44773. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44774. */
  44775. var PBRBaseMaterial = /** @class */ (function (_super) {
  44776. __extends(PBRBaseMaterial, _super);
  44777. /**
  44778. * Instantiates a new PBRMaterial instance.
  44779. *
  44780. * @param name The material name
  44781. * @param scene The scene the material will be use in.
  44782. */
  44783. function PBRBaseMaterial(name, scene) {
  44784. var _this = _super.call(this, name, scene) || this;
  44785. /**
  44786. * Intensity of the direct lights e.g. the four lights available in your scene.
  44787. * This impacts both the direct diffuse and specular highlights.
  44788. */
  44789. _this._directIntensity = 1.0;
  44790. /**
  44791. * Intensity of the emissive part of the material.
  44792. * This helps controlling the emissive effect without modifying the emissive color.
  44793. */
  44794. _this._emissiveIntensity = 1.0;
  44795. /**
  44796. * Intensity of the environment e.g. how much the environment will light the object
  44797. * either through harmonics for rough material or through the refelction for shiny ones.
  44798. */
  44799. _this._environmentIntensity = 1.0;
  44800. /**
  44801. * This is a special control allowing the reduction of the specular highlights coming from the
  44802. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44803. */
  44804. _this._specularIntensity = 1.0;
  44805. /**
  44806. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44807. */
  44808. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44809. /**
  44810. * Debug Control allowing disabling the bump map on this material.
  44811. */
  44812. _this._disableBumpMap = false;
  44813. /**
  44814. * AKA Occlusion Texture Intensity in other nomenclature.
  44815. */
  44816. _this._ambientTextureStrength = 1.0;
  44817. /**
  44818. * The color of a material in ambient lighting.
  44819. */
  44820. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44821. /**
  44822. * AKA Diffuse Color in other nomenclature.
  44823. */
  44824. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44825. /**
  44826. * AKA Specular Color in other nomenclature.
  44827. */
  44828. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44829. /**
  44830. * The color applied when light is reflected from a material.
  44831. */
  44832. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44833. /**
  44834. * The color applied when light is emitted from a material.
  44835. */
  44836. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44837. /**
  44838. * AKA Glossiness in other nomenclature.
  44839. */
  44840. _this._microSurface = 0.9;
  44841. /**
  44842. * source material index of refraction (IOR)' / 'destination material IOR.
  44843. */
  44844. _this._indexOfRefraction = 0.66;
  44845. /**
  44846. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44847. */
  44848. _this._invertRefractionY = false;
  44849. /**
  44850. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44851. * Materials half opaque for instance using refraction could benefit from this control.
  44852. */
  44853. _this._linkRefractionWithTransparency = false;
  44854. /**
  44855. * Specifies that the material will use the light map as a show map.
  44856. */
  44857. _this._useLightmapAsShadowmap = false;
  44858. /**
  44859. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44860. * makes the reflect vector face the model (under horizon).
  44861. */
  44862. _this._useHorizonOcclusion = true;
  44863. /**
  44864. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44865. * too much the area relying on ambient texture to define their ambient occlusion.
  44866. */
  44867. _this._useRadianceOcclusion = true;
  44868. /**
  44869. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44870. */
  44871. _this._useAlphaFromAlbedoTexture = false;
  44872. /**
  44873. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44874. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44875. */
  44876. _this._useSpecularOverAlpha = true;
  44877. /**
  44878. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44879. */
  44880. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44881. /**
  44882. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44883. */
  44884. _this._useRoughnessFromMetallicTextureAlpha = true;
  44885. /**
  44886. * Specifies if the metallic texture contains the roughness information in its green channel.
  44887. */
  44888. _this._useRoughnessFromMetallicTextureGreen = false;
  44889. /**
  44890. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44891. */
  44892. _this._useMetallnessFromMetallicTextureBlue = false;
  44893. /**
  44894. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44895. */
  44896. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44897. /**
  44898. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44899. */
  44900. _this._useAmbientInGrayScale = false;
  44901. /**
  44902. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44903. * The material will try to infer what glossiness each pixel should be.
  44904. */
  44905. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44906. /**
  44907. * BJS is using an harcoded light falloff based on a manually sets up range.
  44908. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44909. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44910. */
  44911. _this._usePhysicalLightFalloff = true;
  44912. /**
  44913. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44914. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44915. */
  44916. _this._useRadianceOverAlpha = true;
  44917. /**
  44918. * Allows using an object space normal map (instead of tangent space).
  44919. */
  44920. _this._useObjectSpaceNormalMap = false;
  44921. /**
  44922. * Allows using the bump map in parallax mode.
  44923. */
  44924. _this._useParallax = false;
  44925. /**
  44926. * Allows using the bump map in parallax occlusion mode.
  44927. */
  44928. _this._useParallaxOcclusion = false;
  44929. /**
  44930. * Controls the scale bias of the parallax mode.
  44931. */
  44932. _this._parallaxScaleBias = 0.05;
  44933. /**
  44934. * If sets to true, disables all the lights affecting the material.
  44935. */
  44936. _this._disableLighting = false;
  44937. /**
  44938. * Number of Simultaneous lights allowed on the material.
  44939. */
  44940. _this._maxSimultaneousLights = 4;
  44941. /**
  44942. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44943. */
  44944. _this._invertNormalMapX = false;
  44945. /**
  44946. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44947. */
  44948. _this._invertNormalMapY = false;
  44949. /**
  44950. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44951. */
  44952. _this._twoSidedLighting = false;
  44953. /**
  44954. * Defines the alpha limits in alpha test mode.
  44955. */
  44956. _this._alphaCutOff = 0.4;
  44957. /**
  44958. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44959. */
  44960. _this._forceAlphaTest = false;
  44961. /**
  44962. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44963. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44964. */
  44965. _this._useAlphaFresnel = false;
  44966. /**
  44967. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44968. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44969. */
  44970. _this._useLinearAlphaFresnel = false;
  44971. /**
  44972. * The transparency mode of the material.
  44973. */
  44974. _this._transparencyMode = null;
  44975. /**
  44976. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44977. * from cos thetav and roughness:
  44978. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44979. */
  44980. _this._environmentBRDFTexture = null;
  44981. /**
  44982. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44983. */
  44984. _this._forceIrradianceInFragment = false;
  44985. /**
  44986. * Force normal to face away from face.
  44987. */
  44988. _this._forceNormalForward = false;
  44989. /**
  44990. * Enables specular anti aliasing in the PBR shader.
  44991. * It will both interacts on the Geometry for analytical and IBL lighting.
  44992. * It also prefilter the roughness map based on the bump values.
  44993. */
  44994. _this._enableSpecularAntiAliasing = false;
  44995. /**
  44996. * Stores the available render targets.
  44997. */
  44998. _this._renderTargets = new BABYLON.SmartArray(16);
  44999. /**
  45000. * Sets the global ambient color for the material used in lighting calculations.
  45001. */
  45002. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45003. /**
  45004. * If set to true, no lighting calculations will be applied.
  45005. */
  45006. _this._unlit = false;
  45007. // Setup the default processing configuration to the scene.
  45008. _this._attachImageProcessingConfiguration(null);
  45009. _this.getRenderTargetTextures = function () {
  45010. _this._renderTargets.reset();
  45011. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45012. _this._renderTargets.push(_this._reflectionTexture);
  45013. }
  45014. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45015. _this._renderTargets.push(_this._refractionTexture);
  45016. }
  45017. return _this._renderTargets;
  45018. };
  45019. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45020. return _this;
  45021. }
  45022. /**
  45023. * Attaches a new image processing configuration to the PBR Material.
  45024. * @param configuration
  45025. */
  45026. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45027. var _this = this;
  45028. if (configuration === this._imageProcessingConfiguration) {
  45029. return;
  45030. }
  45031. // Detaches observer.
  45032. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45033. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45034. }
  45035. // Pick the scene configuration if needed.
  45036. if (!configuration) {
  45037. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45038. }
  45039. else {
  45040. this._imageProcessingConfiguration = configuration;
  45041. }
  45042. // Attaches observer.
  45043. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45044. _this._markAllSubMeshesAsImageProcessingDirty();
  45045. });
  45046. };
  45047. /**
  45048. * Gets the name of the material class.
  45049. */
  45050. PBRBaseMaterial.prototype.getClassName = function () {
  45051. return "PBRBaseMaterial";
  45052. };
  45053. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45054. /**
  45055. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45056. */
  45057. get: function () {
  45058. return this._useLogarithmicDepth;
  45059. },
  45060. /**
  45061. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45062. */
  45063. set: function (value) {
  45064. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45065. },
  45066. enumerable: true,
  45067. configurable: true
  45068. });
  45069. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45070. /**
  45071. * Gets the current transparency mode.
  45072. */
  45073. get: function () {
  45074. return this._transparencyMode;
  45075. },
  45076. /**
  45077. * Sets the transparency mode of the material.
  45078. *
  45079. * | Value | Type | Description |
  45080. * | ----- | ----------------------------------- | ----------- |
  45081. * | 0 | OPAQUE | |
  45082. * | 1 | ALPHATEST | |
  45083. * | 2 | ALPHABLEND | |
  45084. * | 3 | ALPHATESTANDBLEND | |
  45085. *
  45086. */
  45087. set: function (value) {
  45088. if (this._transparencyMode === value) {
  45089. return;
  45090. }
  45091. this._transparencyMode = value;
  45092. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45093. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45094. },
  45095. enumerable: true,
  45096. configurable: true
  45097. });
  45098. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45099. /**
  45100. * Returns true if alpha blending should be disabled.
  45101. */
  45102. get: function () {
  45103. return (this._linkRefractionWithTransparency ||
  45104. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45105. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45106. },
  45107. enumerable: true,
  45108. configurable: true
  45109. });
  45110. /**
  45111. * Specifies whether or not this material should be rendered in alpha blend mode.
  45112. */
  45113. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45114. if (this._disableAlphaBlending) {
  45115. return false;
  45116. }
  45117. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45118. };
  45119. /**
  45120. * Specifies if the mesh will require alpha blending.
  45121. * @param mesh - BJS mesh.
  45122. */
  45123. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45124. if (this._disableAlphaBlending) {
  45125. return false;
  45126. }
  45127. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45128. };
  45129. /**
  45130. * Specifies whether or not this material should be rendered in alpha test mode.
  45131. */
  45132. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45133. if (this._forceAlphaTest) {
  45134. return true;
  45135. }
  45136. if (this._linkRefractionWithTransparency) {
  45137. return false;
  45138. }
  45139. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45140. };
  45141. /**
  45142. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45143. */
  45144. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45145. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45146. };
  45147. /**
  45148. * Gets the texture used for the alpha test.
  45149. */
  45150. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45151. return this._albedoTexture;
  45152. };
  45153. /**
  45154. * Specifies that the submesh is ready to be used.
  45155. * @param mesh - BJS mesh.
  45156. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45157. * @param useInstances - Specifies that instances should be used.
  45158. * @returns - boolean indicating that the submesh is ready or not.
  45159. */
  45160. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45161. if (subMesh.effect && this.isFrozen) {
  45162. if (this._wasPreviouslyReady) {
  45163. return true;
  45164. }
  45165. }
  45166. if (!subMesh._materialDefines) {
  45167. subMesh._materialDefines = new PBRMaterialDefines();
  45168. }
  45169. var defines = subMesh._materialDefines;
  45170. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45171. if (defines._renderId === this.getScene().getRenderId()) {
  45172. return true;
  45173. }
  45174. }
  45175. var scene = this.getScene();
  45176. var engine = scene.getEngine();
  45177. if (defines._areTexturesDirty) {
  45178. if (scene.texturesEnabled) {
  45179. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45180. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45181. return false;
  45182. }
  45183. }
  45184. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45185. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45186. return false;
  45187. }
  45188. }
  45189. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45190. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45191. return false;
  45192. }
  45193. }
  45194. var reflectionTexture = this._getReflectionTexture();
  45195. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45196. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45197. return false;
  45198. }
  45199. }
  45200. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45201. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45202. return false;
  45203. }
  45204. }
  45205. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45206. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45207. return false;
  45208. }
  45209. }
  45210. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45211. if (this._metallicTexture) {
  45212. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45213. return false;
  45214. }
  45215. }
  45216. else if (this._reflectivityTexture) {
  45217. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45218. return false;
  45219. }
  45220. }
  45221. if (this._microSurfaceTexture) {
  45222. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45223. return false;
  45224. }
  45225. }
  45226. }
  45227. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45228. // Bump texture cannot be not blocking.
  45229. if (!this._bumpTexture.isReady()) {
  45230. return false;
  45231. }
  45232. }
  45233. var refractionTexture = this._getRefractionTexture();
  45234. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45235. if (!refractionTexture.isReadyOrNotBlocking()) {
  45236. return false;
  45237. }
  45238. }
  45239. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45240. // This is blocking.
  45241. if (!this._environmentBRDFTexture.isReady()) {
  45242. return false;
  45243. }
  45244. }
  45245. }
  45246. }
  45247. if (defines._areImageProcessingDirty) {
  45248. if (!this._imageProcessingConfiguration.isReady()) {
  45249. return false;
  45250. }
  45251. }
  45252. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45253. mesh.createNormals(true);
  45254. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45255. }
  45256. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45257. if (effect) {
  45258. scene.resetCachedMaterial();
  45259. subMesh.setEffect(effect, defines);
  45260. this.buildUniformLayout();
  45261. }
  45262. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45263. return false;
  45264. }
  45265. defines._renderId = scene.getRenderId();
  45266. this._wasPreviouslyReady = true;
  45267. return true;
  45268. };
  45269. /**
  45270. * Specifies if the material uses metallic roughness workflow.
  45271. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45272. */
  45273. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45274. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45275. return true;
  45276. }
  45277. return false;
  45278. };
  45279. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45280. if (onCompiled === void 0) { onCompiled = null; }
  45281. if (onError === void 0) { onError = null; }
  45282. if (useInstances === void 0) { useInstances = null; }
  45283. if (useClipPlane === void 0) { useClipPlane = null; }
  45284. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45285. if (!defines.isDirty) {
  45286. return null;
  45287. }
  45288. defines.markAsProcessed();
  45289. var scene = this.getScene();
  45290. var engine = scene.getEngine();
  45291. // Fallbacks
  45292. var fallbacks = new BABYLON.EffectFallbacks();
  45293. var fallbackRank = 0;
  45294. if (defines.USESPHERICALINVERTEX) {
  45295. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45296. }
  45297. if (defines.FOG) {
  45298. fallbacks.addFallback(fallbackRank, "FOG");
  45299. }
  45300. if (defines.SPECULARAA) {
  45301. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45302. }
  45303. if (defines.POINTSIZE) {
  45304. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45305. }
  45306. if (defines.LOGARITHMICDEPTH) {
  45307. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45308. }
  45309. if (defines.PARALLAX) {
  45310. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45311. }
  45312. if (defines.PARALLAXOCCLUSION) {
  45313. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45314. }
  45315. if (defines.ENVIRONMENTBRDF) {
  45316. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45317. }
  45318. if (defines.TANGENT) {
  45319. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45320. }
  45321. if (defines.BUMP) {
  45322. fallbacks.addFallback(fallbackRank++, "BUMP");
  45323. }
  45324. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45325. if (defines.SPECULARTERM) {
  45326. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45327. }
  45328. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45329. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45330. }
  45331. if (defines.LIGHTMAP) {
  45332. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45333. }
  45334. if (defines.NORMAL) {
  45335. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45336. }
  45337. if (defines.AMBIENT) {
  45338. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45339. }
  45340. if (defines.EMISSIVE) {
  45341. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45342. }
  45343. if (defines.VERTEXCOLOR) {
  45344. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45345. }
  45346. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45347. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45348. }
  45349. if (defines.MORPHTARGETS) {
  45350. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45351. }
  45352. //Attributes
  45353. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45354. if (defines.NORMAL) {
  45355. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45356. }
  45357. if (defines.TANGENT) {
  45358. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45359. }
  45360. if (defines.UV1) {
  45361. attribs.push(BABYLON.VertexBuffer.UVKind);
  45362. }
  45363. if (defines.UV2) {
  45364. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45365. }
  45366. if (defines.VERTEXCOLOR) {
  45367. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45368. }
  45369. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45370. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45371. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45372. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45373. "vFogInfos", "vFogColor", "pointSize",
  45374. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45375. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45376. "mBones",
  45377. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45378. "vLightingIntensity",
  45379. "logarithmicDepthConstant",
  45380. "vSphericalX", "vSphericalY", "vSphericalZ",
  45381. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45382. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45383. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45384. "vTangentSpaceParams"
  45385. ];
  45386. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45387. "bumpSampler", "lightmapSampler", "opacitySampler",
  45388. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45389. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45390. "microSurfaceSampler", "environmentBrdfSampler"];
  45391. var uniformBuffers = ["Material", "Scene"];
  45392. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45393. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45394. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45395. uniformsNames: uniforms,
  45396. uniformBuffersNames: uniformBuffers,
  45397. samplers: samplers,
  45398. defines: defines,
  45399. maxSimultaneousLights: this._maxSimultaneousLights
  45400. });
  45401. var join = defines.toString();
  45402. return engine.createEffect("pbr", {
  45403. attributes: attribs,
  45404. uniformsNames: uniforms,
  45405. uniformBuffersNames: uniformBuffers,
  45406. samplers: samplers,
  45407. defines: join,
  45408. fallbacks: fallbacks,
  45409. onCompiled: onCompiled,
  45410. onError: onError,
  45411. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45412. }, engine);
  45413. };
  45414. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45415. if (useInstances === void 0) { useInstances = null; }
  45416. if (useClipPlane === void 0) { useClipPlane = null; }
  45417. var scene = this.getScene();
  45418. var engine = scene.getEngine();
  45419. // Lights
  45420. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45421. defines._needNormals = true;
  45422. // Textures
  45423. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45424. if (defines._areTexturesDirty) {
  45425. defines._needUVs = false;
  45426. if (scene.texturesEnabled) {
  45427. if (scene.getEngine().getCaps().textureLOD) {
  45428. defines.LODBASEDMICROSFURACE = true;
  45429. }
  45430. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45431. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45432. }
  45433. else {
  45434. defines.ALBEDO = false;
  45435. }
  45436. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45437. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45438. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45439. }
  45440. else {
  45441. defines.AMBIENT = false;
  45442. }
  45443. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45444. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45445. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45446. }
  45447. else {
  45448. defines.OPACITY = false;
  45449. }
  45450. var reflectionTexture = this._getReflectionTexture();
  45451. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45452. defines.REFLECTION = true;
  45453. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45454. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45455. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45456. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45457. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45458. defines.INVERTCUBICMAP = true;
  45459. }
  45460. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45461. switch (reflectionTexture.coordinatesMode) {
  45462. case BABYLON.Texture.EXPLICIT_MODE:
  45463. defines.REFLECTIONMAP_EXPLICIT = true;
  45464. break;
  45465. case BABYLON.Texture.PLANAR_MODE:
  45466. defines.REFLECTIONMAP_PLANAR = true;
  45467. break;
  45468. case BABYLON.Texture.PROJECTION_MODE:
  45469. defines.REFLECTIONMAP_PROJECTION = true;
  45470. break;
  45471. case BABYLON.Texture.SKYBOX_MODE:
  45472. defines.REFLECTIONMAP_SKYBOX = true;
  45473. break;
  45474. case BABYLON.Texture.SPHERICAL_MODE:
  45475. defines.REFLECTIONMAP_SPHERICAL = true;
  45476. break;
  45477. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45478. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45479. break;
  45480. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45481. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45482. break;
  45483. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45484. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45485. break;
  45486. case BABYLON.Texture.CUBIC_MODE:
  45487. case BABYLON.Texture.INVCUBIC_MODE:
  45488. default:
  45489. defines.REFLECTIONMAP_CUBIC = true;
  45490. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45491. break;
  45492. }
  45493. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45494. if (reflectionTexture.sphericalPolynomial) {
  45495. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45496. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45497. defines.USESPHERICALINVERTEX = false;
  45498. }
  45499. else {
  45500. defines.USESPHERICALINVERTEX = true;
  45501. }
  45502. }
  45503. }
  45504. }
  45505. else {
  45506. defines.REFLECTION = false;
  45507. defines.REFLECTIONMAP_3D = false;
  45508. defines.REFLECTIONMAP_SPHERICAL = false;
  45509. defines.REFLECTIONMAP_PLANAR = false;
  45510. defines.REFLECTIONMAP_CUBIC = false;
  45511. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45512. defines.REFLECTIONMAP_PROJECTION = false;
  45513. defines.REFLECTIONMAP_SKYBOX = false;
  45514. defines.REFLECTIONMAP_EXPLICIT = false;
  45515. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45516. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45517. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45518. defines.INVERTCUBICMAP = false;
  45519. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45520. defines.USESPHERICALINVERTEX = false;
  45521. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45522. defines.LODINREFLECTIONALPHA = false;
  45523. defines.GAMMAREFLECTION = false;
  45524. defines.RGBDREFLECTION = false;
  45525. }
  45526. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45527. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45528. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45529. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45530. }
  45531. else {
  45532. defines.LIGHTMAP = false;
  45533. }
  45534. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45535. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45536. }
  45537. else {
  45538. defines.EMISSIVE = false;
  45539. }
  45540. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45541. if (this._metallicTexture) {
  45542. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45543. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45544. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45545. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45546. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45547. }
  45548. else if (this._reflectivityTexture) {
  45549. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45550. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45551. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45552. }
  45553. else {
  45554. defines.REFLECTIVITY = false;
  45555. }
  45556. if (this._microSurfaceTexture) {
  45557. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45558. }
  45559. else {
  45560. defines.MICROSURFACEMAP = false;
  45561. }
  45562. }
  45563. else {
  45564. defines.REFLECTIVITY = false;
  45565. defines.MICROSURFACEMAP = false;
  45566. }
  45567. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45568. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45569. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45570. defines.PARALLAX = true;
  45571. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45572. }
  45573. else {
  45574. defines.PARALLAX = false;
  45575. }
  45576. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45577. }
  45578. else {
  45579. defines.BUMP = false;
  45580. }
  45581. var refractionTexture = this._getRefractionTexture();
  45582. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45583. defines.REFRACTION = true;
  45584. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45585. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45586. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45587. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45588. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45589. if (this._linkRefractionWithTransparency) {
  45590. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45591. }
  45592. }
  45593. else {
  45594. defines.REFRACTION = false;
  45595. }
  45596. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45597. defines.ENVIRONMENTBRDF = true;
  45598. }
  45599. else {
  45600. defines.ENVIRONMENTBRDF = false;
  45601. }
  45602. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45603. defines.ALPHAFROMALBEDO = true;
  45604. }
  45605. else {
  45606. defines.ALPHAFROMALBEDO = false;
  45607. }
  45608. }
  45609. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45610. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45611. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45612. if (!this.backFaceCulling && this._twoSidedLighting) {
  45613. defines.TWOSIDEDLIGHTING = true;
  45614. }
  45615. else {
  45616. defines.TWOSIDEDLIGHTING = false;
  45617. }
  45618. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45619. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45620. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45621. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45622. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45623. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45624. }
  45625. if (defines._areImageProcessingDirty) {
  45626. this._imageProcessingConfiguration.prepareDefines(defines);
  45627. }
  45628. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45629. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45630. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45631. // Misc.
  45632. if (defines._areMiscDirty) {
  45633. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45634. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45635. }
  45636. // Values that need to be evaluated on every frame
  45637. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45638. // Attribs
  45639. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45640. };
  45641. /**
  45642. * Force shader compilation
  45643. */
  45644. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45645. var _this = this;
  45646. var localOptions = __assign({ clipPlane: false }, options);
  45647. var defines = new PBRMaterialDefines();
  45648. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45649. if (effect.isReady()) {
  45650. if (onCompiled) {
  45651. onCompiled(this);
  45652. }
  45653. }
  45654. else {
  45655. effect.onCompileObservable.add(function () {
  45656. if (onCompiled) {
  45657. onCompiled(_this);
  45658. }
  45659. });
  45660. }
  45661. };
  45662. /**
  45663. * Initializes the uniform buffer layout for the shader.
  45664. */
  45665. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45666. // Order is important !
  45667. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45668. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45669. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45670. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45671. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45672. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45673. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45674. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45675. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45676. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45677. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45678. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45679. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45680. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45681. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45682. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45683. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45684. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45685. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45686. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45687. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45688. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45689. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45690. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45691. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45692. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45693. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45694. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45695. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45696. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45697. this._uniformBuffer.addUniform("pointSize", 1);
  45698. this._uniformBuffer.create();
  45699. };
  45700. /**
  45701. * Unbinds the textures.
  45702. */
  45703. PBRBaseMaterial.prototype.unbind = function () {
  45704. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45705. this._uniformBuffer.setTexture("reflectionSampler", null);
  45706. }
  45707. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45708. this._uniformBuffer.setTexture("refractionSampler", null);
  45709. }
  45710. _super.prototype.unbind.call(this);
  45711. };
  45712. /**
  45713. * Binds the submesh data.
  45714. * @param world - The world matrix.
  45715. * @param mesh - The BJS mesh.
  45716. * @param subMesh - A submesh of the BJS mesh.
  45717. */
  45718. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45719. var scene = this.getScene();
  45720. var defines = subMesh._materialDefines;
  45721. if (!defines) {
  45722. return;
  45723. }
  45724. var effect = subMesh.effect;
  45725. if (!effect) {
  45726. return;
  45727. }
  45728. this._activeEffect = effect;
  45729. // Matrices
  45730. this.bindOnlyWorldMatrix(world);
  45731. // Normal Matrix
  45732. if (defines.OBJECTSPACE_NORMALMAP) {
  45733. world.toNormalMatrix(this._normalMatrix);
  45734. this.bindOnlyNormalMatrix(this._normalMatrix);
  45735. }
  45736. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45737. // Bones
  45738. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45739. var reflectionTexture = null;
  45740. if (mustRebind) {
  45741. this._uniformBuffer.bindToEffect(effect, "Material");
  45742. this.bindViewProjection(effect);
  45743. reflectionTexture = this._getReflectionTexture();
  45744. var refractionTexture = this._getRefractionTexture();
  45745. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45746. // Texture uniforms
  45747. if (scene.texturesEnabled) {
  45748. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45749. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45750. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45751. }
  45752. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45753. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45754. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45755. }
  45756. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45757. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45758. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45759. }
  45760. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45761. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45762. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45763. if (reflectionTexture.boundingBoxSize) {
  45764. var cubeTexture = reflectionTexture;
  45765. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45766. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45767. }
  45768. var polynomials = reflectionTexture.sphericalPolynomial;
  45769. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45770. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45771. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45772. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45773. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45774. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45775. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45776. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45777. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45778. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45779. }
  45780. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45781. }
  45782. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45783. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45784. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45785. }
  45786. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45787. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45788. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45789. }
  45790. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45791. if (this._metallicTexture) {
  45792. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45793. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45794. }
  45795. else if (this._reflectivityTexture) {
  45796. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45797. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45798. }
  45799. if (this._microSurfaceTexture) {
  45800. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45801. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45802. }
  45803. }
  45804. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45805. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45806. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45807. if (scene._mirroredCameraPosition) {
  45808. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45809. }
  45810. else {
  45811. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45812. }
  45813. }
  45814. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45815. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45816. var depth = 1.0;
  45817. if (!refractionTexture.isCube) {
  45818. if (refractionTexture.depth) {
  45819. depth = refractionTexture.depth;
  45820. }
  45821. }
  45822. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45823. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45824. }
  45825. }
  45826. // Point size
  45827. if (this.pointsCloud) {
  45828. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45829. }
  45830. // Colors
  45831. if (defines.METALLICWORKFLOW) {
  45832. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45833. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45834. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45835. }
  45836. else {
  45837. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45838. }
  45839. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45840. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45841. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45842. // Misc
  45843. this._lightingInfos.x = this._directIntensity;
  45844. this._lightingInfos.y = this._emissiveIntensity;
  45845. this._lightingInfos.z = this._environmentIntensity;
  45846. this._lightingInfos.w = this._specularIntensity;
  45847. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45848. }
  45849. // Textures
  45850. if (scene.texturesEnabled) {
  45851. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45852. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45853. }
  45854. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45855. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45856. }
  45857. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45858. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45859. }
  45860. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45861. if (defines.LODBASEDMICROSFURACE) {
  45862. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45863. }
  45864. else {
  45865. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45866. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45867. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45868. }
  45869. }
  45870. if (defines.ENVIRONMENTBRDF) {
  45871. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45872. }
  45873. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45874. if (defines.LODBASEDMICROSFURACE) {
  45875. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45876. }
  45877. else {
  45878. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45879. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45880. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45881. }
  45882. }
  45883. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45884. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45885. }
  45886. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45887. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45888. }
  45889. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45890. if (this._metallicTexture) {
  45891. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45892. }
  45893. else if (this._reflectivityTexture) {
  45894. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45895. }
  45896. if (this._microSurfaceTexture) {
  45897. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45898. }
  45899. }
  45900. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45901. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45902. }
  45903. }
  45904. // Clip plane
  45905. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45906. // Colors
  45907. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45908. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45909. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45910. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45911. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45912. }
  45913. if (mustRebind || !this.isFrozen) {
  45914. // Lights
  45915. if (scene.lightsEnabled && !this._disableLighting) {
  45916. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45917. }
  45918. // View
  45919. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45920. this.bindView(effect);
  45921. }
  45922. // Fog
  45923. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45924. // Morph targets
  45925. if (defines.NUM_MORPH_INFLUENCERS) {
  45926. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45927. }
  45928. // image processing
  45929. this._imageProcessingConfiguration.bind(this._activeEffect);
  45930. // Log. depth
  45931. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45932. }
  45933. this._uniformBuffer.update();
  45934. this._afterBind(mesh, this._activeEffect);
  45935. };
  45936. /**
  45937. * Returns the animatable textures.
  45938. * @returns - Array of animatable textures.
  45939. */
  45940. PBRBaseMaterial.prototype.getAnimatables = function () {
  45941. var results = [];
  45942. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45943. results.push(this._albedoTexture);
  45944. }
  45945. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45946. results.push(this._ambientTexture);
  45947. }
  45948. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45949. results.push(this._opacityTexture);
  45950. }
  45951. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45952. results.push(this._reflectionTexture);
  45953. }
  45954. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45955. results.push(this._emissiveTexture);
  45956. }
  45957. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45958. results.push(this._metallicTexture);
  45959. }
  45960. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45961. results.push(this._reflectivityTexture);
  45962. }
  45963. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45964. results.push(this._bumpTexture);
  45965. }
  45966. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45967. results.push(this._lightmapTexture);
  45968. }
  45969. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45970. results.push(this._refractionTexture);
  45971. }
  45972. return results;
  45973. };
  45974. /**
  45975. * Returns the texture used for reflections.
  45976. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45977. */
  45978. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45979. if (this._reflectionTexture) {
  45980. return this._reflectionTexture;
  45981. }
  45982. return this.getScene().environmentTexture;
  45983. };
  45984. /**
  45985. * Returns the texture used for refraction or null if none is used.
  45986. * @returns - Refection texture if present. If no refraction texture and refraction
  45987. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45988. */
  45989. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45990. if (this._refractionTexture) {
  45991. return this._refractionTexture;
  45992. }
  45993. if (this._linkRefractionWithTransparency) {
  45994. return this.getScene().environmentTexture;
  45995. }
  45996. return null;
  45997. };
  45998. /**
  45999. * Disposes the resources of the material.
  46000. * @param forceDisposeEffect - Forces the disposal of effects.
  46001. * @param forceDisposeTextures - Forces the disposal of all textures.
  46002. */
  46003. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46004. if (forceDisposeTextures) {
  46005. if (this._albedoTexture) {
  46006. this._albedoTexture.dispose();
  46007. }
  46008. if (this._ambientTexture) {
  46009. this._ambientTexture.dispose();
  46010. }
  46011. if (this._opacityTexture) {
  46012. this._opacityTexture.dispose();
  46013. }
  46014. if (this._reflectionTexture) {
  46015. this._reflectionTexture.dispose();
  46016. }
  46017. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46018. this._environmentBRDFTexture.dispose();
  46019. }
  46020. if (this._emissiveTexture) {
  46021. this._emissiveTexture.dispose();
  46022. }
  46023. if (this._metallicTexture) {
  46024. this._metallicTexture.dispose();
  46025. }
  46026. if (this._reflectivityTexture) {
  46027. this._reflectivityTexture.dispose();
  46028. }
  46029. if (this._bumpTexture) {
  46030. this._bumpTexture.dispose();
  46031. }
  46032. if (this._lightmapTexture) {
  46033. this._lightmapTexture.dispose();
  46034. }
  46035. if (this._refractionTexture) {
  46036. this._refractionTexture.dispose();
  46037. }
  46038. }
  46039. this._renderTargets.dispose();
  46040. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46041. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46042. }
  46043. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46044. };
  46045. /**
  46046. * Stores the reflectivity values based on metallic roughness workflow.
  46047. */
  46048. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46049. __decorate([
  46050. BABYLON.serializeAsImageProcessingConfiguration()
  46051. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46052. __decorate([
  46053. BABYLON.serialize()
  46054. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46055. __decorate([
  46056. BABYLON.serialize()
  46057. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46058. return PBRBaseMaterial;
  46059. }(BABYLON.PushMaterial));
  46060. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46061. })(BABYLON || (BABYLON = {}));
  46062. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46063. var BABYLON;
  46064. (function (BABYLON) {
  46065. /**
  46066. * The Physically based simple base material of BJS.
  46067. *
  46068. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46069. * It is used as the base class for both the specGloss and metalRough conventions.
  46070. */
  46071. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46072. __extends(PBRBaseSimpleMaterial, _super);
  46073. /**
  46074. * Instantiates a new PBRMaterial instance.
  46075. *
  46076. * @param name The material name
  46077. * @param scene The scene the material will be use in.
  46078. */
  46079. function PBRBaseSimpleMaterial(name, scene) {
  46080. var _this = _super.call(this, name, scene) || this;
  46081. /**
  46082. * Number of Simultaneous lights allowed on the material.
  46083. */
  46084. _this.maxSimultaneousLights = 4;
  46085. /**
  46086. * If sets to true, disables all the lights affecting the material.
  46087. */
  46088. _this.disableLighting = false;
  46089. /**
  46090. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46091. */
  46092. _this.invertNormalMapX = false;
  46093. /**
  46094. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46095. */
  46096. _this.invertNormalMapY = false;
  46097. /**
  46098. * Emissivie color used to self-illuminate the model.
  46099. */
  46100. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46101. /**
  46102. * Occlusion Channel Strenght.
  46103. */
  46104. _this.occlusionStrength = 1.0;
  46105. _this.useLightmapAsShadowmap = false;
  46106. _this._useAlphaFromAlbedoTexture = true;
  46107. _this._useAmbientInGrayScale = true;
  46108. return _this;
  46109. }
  46110. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46111. /**
  46112. * Gets the current double sided mode.
  46113. */
  46114. get: function () {
  46115. return this._twoSidedLighting;
  46116. },
  46117. /**
  46118. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46119. */
  46120. set: function (value) {
  46121. if (this._twoSidedLighting === value) {
  46122. return;
  46123. }
  46124. this._twoSidedLighting = value;
  46125. this.backFaceCulling = !value;
  46126. this._markAllSubMeshesAsTexturesDirty();
  46127. },
  46128. enumerable: true,
  46129. configurable: true
  46130. });
  46131. /**
  46132. * Return the active textures of the material.
  46133. */
  46134. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46135. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46136. if (this.environmentTexture) {
  46137. activeTextures.push(this.environmentTexture);
  46138. }
  46139. if (this.normalTexture) {
  46140. activeTextures.push(this.normalTexture);
  46141. }
  46142. if (this.emissiveTexture) {
  46143. activeTextures.push(this.emissiveTexture);
  46144. }
  46145. if (this.occlusionTexture) {
  46146. activeTextures.push(this.occlusionTexture);
  46147. }
  46148. if (this.lightmapTexture) {
  46149. activeTextures.push(this.lightmapTexture);
  46150. }
  46151. return activeTextures;
  46152. };
  46153. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46154. if (_super.prototype.hasTexture.call(this, texture)) {
  46155. return true;
  46156. }
  46157. if (this.lightmapTexture === texture) {
  46158. return true;
  46159. }
  46160. return false;
  46161. };
  46162. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46163. return "PBRBaseSimpleMaterial";
  46164. };
  46165. __decorate([
  46166. BABYLON.serialize(),
  46167. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46168. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46169. __decorate([
  46170. BABYLON.serialize(),
  46171. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46172. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46173. __decorate([
  46174. BABYLON.serializeAsTexture(),
  46175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46176. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46177. __decorate([
  46178. BABYLON.serialize(),
  46179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46180. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46181. __decorate([
  46182. BABYLON.serialize(),
  46183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46184. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46185. __decorate([
  46186. BABYLON.serializeAsTexture(),
  46187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46188. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46189. __decorate([
  46190. BABYLON.serializeAsColor3("emissive"),
  46191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46192. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46193. __decorate([
  46194. BABYLON.serializeAsTexture(),
  46195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46196. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46197. __decorate([
  46198. BABYLON.serialize(),
  46199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46200. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46201. __decorate([
  46202. BABYLON.serializeAsTexture(),
  46203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46204. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46205. __decorate([
  46206. BABYLON.serialize(),
  46207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46208. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46209. __decorate([
  46210. BABYLON.serialize()
  46211. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46212. __decorate([
  46213. BABYLON.serializeAsTexture(),
  46214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46215. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46216. __decorate([
  46217. BABYLON.serialize(),
  46218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46219. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46220. return PBRBaseSimpleMaterial;
  46221. }(BABYLON.PBRBaseMaterial));
  46222. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46223. })(BABYLON || (BABYLON = {}));
  46224. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46225. var BABYLON;
  46226. (function (BABYLON) {
  46227. /**
  46228. * The Physically based material of BJS.
  46229. *
  46230. * This offers the main features of a standard PBR material.
  46231. * For more information, please refer to the documentation :
  46232. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46233. */
  46234. var PBRMaterial = /** @class */ (function (_super) {
  46235. __extends(PBRMaterial, _super);
  46236. /**
  46237. * Instantiates a new PBRMaterial instance.
  46238. *
  46239. * @param name The material name
  46240. * @param scene The scene the material will be use in.
  46241. */
  46242. function PBRMaterial(name, scene) {
  46243. var _this = _super.call(this, name, scene) || this;
  46244. /**
  46245. * Intensity of the direct lights e.g. the four lights available in your scene.
  46246. * This impacts both the direct diffuse and specular highlights.
  46247. */
  46248. _this.directIntensity = 1.0;
  46249. /**
  46250. * Intensity of the emissive part of the material.
  46251. * This helps controlling the emissive effect without modifying the emissive color.
  46252. */
  46253. _this.emissiveIntensity = 1.0;
  46254. /**
  46255. * Intensity of the environment e.g. how much the environment will light the object
  46256. * either through harmonics for rough material or through the refelction for shiny ones.
  46257. */
  46258. _this.environmentIntensity = 1.0;
  46259. /**
  46260. * This is a special control allowing the reduction of the specular highlights coming from the
  46261. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46262. */
  46263. _this.specularIntensity = 1.0;
  46264. /**
  46265. * Debug Control allowing disabling the bump map on this material.
  46266. */
  46267. _this.disableBumpMap = false;
  46268. /**
  46269. * AKA Occlusion Texture Intensity in other nomenclature.
  46270. */
  46271. _this.ambientTextureStrength = 1.0;
  46272. /**
  46273. * The color of a material in ambient lighting.
  46274. */
  46275. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46276. /**
  46277. * AKA Diffuse Color in other nomenclature.
  46278. */
  46279. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46280. /**
  46281. * AKA Specular Color in other nomenclature.
  46282. */
  46283. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46284. /**
  46285. * The color reflected from the material.
  46286. */
  46287. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46288. /**
  46289. * The color emitted from the material.
  46290. */
  46291. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46292. /**
  46293. * AKA Glossiness in other nomenclature.
  46294. */
  46295. _this.microSurface = 1.0;
  46296. /**
  46297. * source material index of refraction (IOR)' / 'destination material IOR.
  46298. */
  46299. _this.indexOfRefraction = 0.66;
  46300. /**
  46301. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46302. */
  46303. _this.invertRefractionY = false;
  46304. /**
  46305. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46306. * Materials half opaque for instance using refraction could benefit from this control.
  46307. */
  46308. _this.linkRefractionWithTransparency = false;
  46309. _this.useLightmapAsShadowmap = false;
  46310. /**
  46311. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46312. */
  46313. _this.useAlphaFromAlbedoTexture = false;
  46314. /**
  46315. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46316. */
  46317. _this.forceAlphaTest = false;
  46318. /**
  46319. * Defines the alpha limits in alpha test mode.
  46320. */
  46321. _this.alphaCutOff = 0.4;
  46322. /**
  46323. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46324. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46325. */
  46326. _this.useSpecularOverAlpha = true;
  46327. /**
  46328. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46329. */
  46330. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46331. /**
  46332. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46333. */
  46334. _this.useRoughnessFromMetallicTextureAlpha = true;
  46335. /**
  46336. * Specifies if the metallic texture contains the roughness information in its green channel.
  46337. */
  46338. _this.useRoughnessFromMetallicTextureGreen = false;
  46339. /**
  46340. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46341. */
  46342. _this.useMetallnessFromMetallicTextureBlue = false;
  46343. /**
  46344. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46345. */
  46346. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46347. /**
  46348. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46349. */
  46350. _this.useAmbientInGrayScale = false;
  46351. /**
  46352. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46353. * The material will try to infer what glossiness each pixel should be.
  46354. */
  46355. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46356. /**
  46357. * BJS is using an harcoded light falloff based on a manually sets up range.
  46358. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46359. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46360. */
  46361. _this.usePhysicalLightFalloff = true;
  46362. /**
  46363. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46364. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46365. */
  46366. _this.useRadianceOverAlpha = true;
  46367. /**
  46368. * Allows using an object space normal map (instead of tangent space).
  46369. */
  46370. _this.useObjectSpaceNormalMap = false;
  46371. /**
  46372. * Allows using the bump map in parallax mode.
  46373. */
  46374. _this.useParallax = false;
  46375. /**
  46376. * Allows using the bump map in parallax occlusion mode.
  46377. */
  46378. _this.useParallaxOcclusion = false;
  46379. /**
  46380. * Controls the scale bias of the parallax mode.
  46381. */
  46382. _this.parallaxScaleBias = 0.05;
  46383. /**
  46384. * If sets to true, disables all the lights affecting the material.
  46385. */
  46386. _this.disableLighting = false;
  46387. /**
  46388. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46389. */
  46390. _this.forceIrradianceInFragment = false;
  46391. /**
  46392. * Number of Simultaneous lights allowed on the material.
  46393. */
  46394. _this.maxSimultaneousLights = 4;
  46395. /**
  46396. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46397. */
  46398. _this.invertNormalMapX = false;
  46399. /**
  46400. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46401. */
  46402. _this.invertNormalMapY = false;
  46403. /**
  46404. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46405. */
  46406. _this.twoSidedLighting = false;
  46407. /**
  46408. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46409. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46410. */
  46411. _this.useAlphaFresnel = false;
  46412. /**
  46413. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46414. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46415. */
  46416. _this.useLinearAlphaFresnel = false;
  46417. /**
  46418. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46419. * And/Or occlude the blended part.
  46420. */
  46421. _this.environmentBRDFTexture = null;
  46422. /**
  46423. * Force normal to face away from face.
  46424. */
  46425. _this.forceNormalForward = false;
  46426. /**
  46427. * Enables specular anti aliasing in the PBR shader.
  46428. * It will both interacts on the Geometry for analytical and IBL lighting.
  46429. * It also prefilter the roughness map based on the bump values.
  46430. */
  46431. _this.enableSpecularAntiAliasing = false;
  46432. /**
  46433. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46434. * makes the reflect vector face the model (under horizon).
  46435. */
  46436. _this.useHorizonOcclusion = true;
  46437. /**
  46438. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46439. * too much the area relying on ambient texture to define their ambient occlusion.
  46440. */
  46441. _this.useRadianceOcclusion = true;
  46442. /**
  46443. * If set to true, no lighting calculations will be applied.
  46444. */
  46445. _this.unlit = false;
  46446. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46447. return _this;
  46448. }
  46449. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46450. /**
  46451. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46452. */
  46453. get: function () {
  46454. return this._PBRMATERIAL_OPAQUE;
  46455. },
  46456. enumerable: true,
  46457. configurable: true
  46458. });
  46459. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46460. /**
  46461. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46462. */
  46463. get: function () {
  46464. return this._PBRMATERIAL_ALPHATEST;
  46465. },
  46466. enumerable: true,
  46467. configurable: true
  46468. });
  46469. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46470. /**
  46471. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46472. */
  46473. get: function () {
  46474. return this._PBRMATERIAL_ALPHABLEND;
  46475. },
  46476. enumerable: true,
  46477. configurable: true
  46478. });
  46479. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46480. /**
  46481. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46482. * They are also discarded below the alpha cutoff threshold to improve performances.
  46483. */
  46484. get: function () {
  46485. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46486. },
  46487. enumerable: true,
  46488. configurable: true
  46489. });
  46490. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46491. /**
  46492. * Gets the image processing configuration used either in this material.
  46493. */
  46494. get: function () {
  46495. return this._imageProcessingConfiguration;
  46496. },
  46497. /**
  46498. * Sets the Default image processing configuration used either in the this material.
  46499. *
  46500. * If sets to null, the scene one is in use.
  46501. */
  46502. set: function (value) {
  46503. this._attachImageProcessingConfiguration(value);
  46504. // Ensure the effect will be rebuilt.
  46505. this._markAllSubMeshesAsTexturesDirty();
  46506. },
  46507. enumerable: true,
  46508. configurable: true
  46509. });
  46510. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46511. /**
  46512. * Gets wether the color curves effect is enabled.
  46513. */
  46514. get: function () {
  46515. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46516. },
  46517. /**
  46518. * Sets wether the color curves effect is enabled.
  46519. */
  46520. set: function (value) {
  46521. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46522. },
  46523. enumerable: true,
  46524. configurable: true
  46525. });
  46526. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46527. /**
  46528. * Gets wether the color grading effect is enabled.
  46529. */
  46530. get: function () {
  46531. return this.imageProcessingConfiguration.colorGradingEnabled;
  46532. },
  46533. /**
  46534. * Gets wether the color grading effect is enabled.
  46535. */
  46536. set: function (value) {
  46537. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46538. },
  46539. enumerable: true,
  46540. configurable: true
  46541. });
  46542. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46543. /**
  46544. * Gets wether tonemapping is enabled or not.
  46545. */
  46546. get: function () {
  46547. return this._imageProcessingConfiguration.toneMappingEnabled;
  46548. },
  46549. /**
  46550. * Sets wether tonemapping is enabled or not
  46551. */
  46552. set: function (value) {
  46553. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46554. },
  46555. enumerable: true,
  46556. configurable: true
  46557. });
  46558. ;
  46559. ;
  46560. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46561. /**
  46562. * The camera exposure used on this material.
  46563. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46564. * This corresponds to a photographic exposure.
  46565. */
  46566. get: function () {
  46567. return this._imageProcessingConfiguration.exposure;
  46568. },
  46569. /**
  46570. * The camera exposure used on this material.
  46571. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46572. * This corresponds to a photographic exposure.
  46573. */
  46574. set: function (value) {
  46575. this._imageProcessingConfiguration.exposure = value;
  46576. },
  46577. enumerable: true,
  46578. configurable: true
  46579. });
  46580. ;
  46581. ;
  46582. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46583. /**
  46584. * Gets The camera contrast used on this material.
  46585. */
  46586. get: function () {
  46587. return this._imageProcessingConfiguration.contrast;
  46588. },
  46589. /**
  46590. * Sets The camera contrast used on this material.
  46591. */
  46592. set: function (value) {
  46593. this._imageProcessingConfiguration.contrast = value;
  46594. },
  46595. enumerable: true,
  46596. configurable: true
  46597. });
  46598. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46599. /**
  46600. * Gets the Color Grading 2D Lookup Texture.
  46601. */
  46602. get: function () {
  46603. return this._imageProcessingConfiguration.colorGradingTexture;
  46604. },
  46605. /**
  46606. * Sets the Color Grading 2D Lookup Texture.
  46607. */
  46608. set: function (value) {
  46609. this._imageProcessingConfiguration.colorGradingTexture = value;
  46610. },
  46611. enumerable: true,
  46612. configurable: true
  46613. });
  46614. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46615. /**
  46616. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46617. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46618. * 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;
  46619. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46620. */
  46621. get: function () {
  46622. return this._imageProcessingConfiguration.colorCurves;
  46623. },
  46624. /**
  46625. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46626. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46627. * 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;
  46628. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46629. */
  46630. set: function (value) {
  46631. this._imageProcessingConfiguration.colorCurves = value;
  46632. },
  46633. enumerable: true,
  46634. configurable: true
  46635. });
  46636. /**
  46637. * Returns the name of this material class.
  46638. */
  46639. PBRMaterial.prototype.getClassName = function () {
  46640. return "PBRMaterial";
  46641. };
  46642. /**
  46643. * Returns an array of the actively used textures.
  46644. * @returns - Array of BaseTextures
  46645. */
  46646. PBRMaterial.prototype.getActiveTextures = function () {
  46647. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46648. if (this._albedoTexture) {
  46649. activeTextures.push(this._albedoTexture);
  46650. }
  46651. if (this._ambientTexture) {
  46652. activeTextures.push(this._ambientTexture);
  46653. }
  46654. if (this._opacityTexture) {
  46655. activeTextures.push(this._opacityTexture);
  46656. }
  46657. if (this._reflectionTexture) {
  46658. activeTextures.push(this._reflectionTexture);
  46659. }
  46660. if (this._emissiveTexture) {
  46661. activeTextures.push(this._emissiveTexture);
  46662. }
  46663. if (this._reflectivityTexture) {
  46664. activeTextures.push(this._reflectivityTexture);
  46665. }
  46666. if (this._metallicTexture) {
  46667. activeTextures.push(this._metallicTexture);
  46668. }
  46669. if (this._microSurfaceTexture) {
  46670. activeTextures.push(this._microSurfaceTexture);
  46671. }
  46672. if (this._bumpTexture) {
  46673. activeTextures.push(this._bumpTexture);
  46674. }
  46675. if (this._lightmapTexture) {
  46676. activeTextures.push(this._lightmapTexture);
  46677. }
  46678. if (this._refractionTexture) {
  46679. activeTextures.push(this._refractionTexture);
  46680. }
  46681. return activeTextures;
  46682. };
  46683. /**
  46684. * Checks to see if a texture is used in the material.
  46685. * @param texture - Base texture to use.
  46686. * @returns - Boolean specifying if a texture is used in the material.
  46687. */
  46688. PBRMaterial.prototype.hasTexture = function (texture) {
  46689. if (_super.prototype.hasTexture.call(this, texture)) {
  46690. return true;
  46691. }
  46692. if (this._albedoTexture === texture) {
  46693. return true;
  46694. }
  46695. if (this._ambientTexture === texture) {
  46696. return true;
  46697. }
  46698. if (this._opacityTexture === texture) {
  46699. return true;
  46700. }
  46701. if (this._reflectionTexture === texture) {
  46702. return true;
  46703. }
  46704. if (this._reflectivityTexture === texture) {
  46705. return true;
  46706. }
  46707. if (this._metallicTexture === texture) {
  46708. return true;
  46709. }
  46710. if (this._microSurfaceTexture === texture) {
  46711. return true;
  46712. }
  46713. if (this._bumpTexture === texture) {
  46714. return true;
  46715. }
  46716. if (this._lightmapTexture === texture) {
  46717. return true;
  46718. }
  46719. if (this._refractionTexture === texture) {
  46720. return true;
  46721. }
  46722. return false;
  46723. };
  46724. /**
  46725. * Makes a duplicate of the current material.
  46726. * @param name - name to use for the new material.
  46727. */
  46728. PBRMaterial.prototype.clone = function (name) {
  46729. var _this = this;
  46730. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46731. clone.id = name;
  46732. clone.name = name;
  46733. return clone;
  46734. };
  46735. /**
  46736. * Serializes this PBR Material.
  46737. * @returns - An object with the serialized material.
  46738. */
  46739. PBRMaterial.prototype.serialize = function () {
  46740. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46741. serializationObject.customType = "BABYLON.PBRMaterial";
  46742. return serializationObject;
  46743. };
  46744. // Statics
  46745. /**
  46746. * Parses a PBR Material from a serialized object.
  46747. * @param source - Serialized object.
  46748. * @param scene - BJS scene instance.
  46749. * @param rootUrl - url for the scene object
  46750. * @returns - PBRMaterial
  46751. */
  46752. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46753. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46754. };
  46755. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46756. /**
  46757. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46758. */
  46759. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46760. /**
  46761. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46762. */
  46763. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46764. /**
  46765. * 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.
  46766. * They are also discarded below the alpha cutoff threshold to improve performances.
  46767. */
  46768. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46769. __decorate([
  46770. BABYLON.serialize(),
  46771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46772. ], PBRMaterial.prototype, "directIntensity", void 0);
  46773. __decorate([
  46774. BABYLON.serialize(),
  46775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46776. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46777. __decorate([
  46778. BABYLON.serialize(),
  46779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46780. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46781. __decorate([
  46782. BABYLON.serialize(),
  46783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46784. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46785. __decorate([
  46786. BABYLON.serialize(),
  46787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46788. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46789. __decorate([
  46790. BABYLON.serializeAsTexture(),
  46791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46792. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46793. __decorate([
  46794. BABYLON.serializeAsTexture(),
  46795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46796. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46797. __decorate([
  46798. BABYLON.serialize(),
  46799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46800. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46801. __decorate([
  46802. BABYLON.serializeAsTexture(),
  46803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46804. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46805. __decorate([
  46806. BABYLON.serializeAsTexture(),
  46807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46808. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46809. __decorate([
  46810. BABYLON.serializeAsTexture(),
  46811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46812. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46813. __decorate([
  46814. BABYLON.serializeAsTexture(),
  46815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46816. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46817. __decorate([
  46818. BABYLON.serializeAsTexture(),
  46819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46820. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46821. __decorate([
  46822. BABYLON.serialize(),
  46823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46824. ], PBRMaterial.prototype, "metallic", void 0);
  46825. __decorate([
  46826. BABYLON.serialize(),
  46827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46828. ], PBRMaterial.prototype, "roughness", void 0);
  46829. __decorate([
  46830. BABYLON.serializeAsTexture(),
  46831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46832. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46833. __decorate([
  46834. BABYLON.serializeAsTexture(),
  46835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46836. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46837. __decorate([
  46838. BABYLON.serializeAsTexture(),
  46839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46840. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46841. __decorate([
  46842. BABYLON.serializeAsTexture(),
  46843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46844. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46845. __decorate([
  46846. BABYLON.serializeAsColor3("ambient"),
  46847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46848. ], PBRMaterial.prototype, "ambientColor", void 0);
  46849. __decorate([
  46850. BABYLON.serializeAsColor3("albedo"),
  46851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46852. ], PBRMaterial.prototype, "albedoColor", void 0);
  46853. __decorate([
  46854. BABYLON.serializeAsColor3("reflectivity"),
  46855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46856. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46857. __decorate([
  46858. BABYLON.serializeAsColor3("reflection"),
  46859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46860. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46861. __decorate([
  46862. BABYLON.serializeAsColor3("emissive"),
  46863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46864. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46865. __decorate([
  46866. BABYLON.serialize(),
  46867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46868. ], PBRMaterial.prototype, "microSurface", void 0);
  46869. __decorate([
  46870. BABYLON.serialize(),
  46871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46872. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46873. __decorate([
  46874. BABYLON.serialize(),
  46875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46876. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46877. __decorate([
  46878. BABYLON.serialize(),
  46879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46880. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46881. __decorate([
  46882. BABYLON.serialize(),
  46883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46884. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46885. __decorate([
  46886. BABYLON.serialize(),
  46887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46888. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46889. __decorate([
  46890. BABYLON.serialize(),
  46891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46892. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46893. __decorate([
  46894. BABYLON.serialize(),
  46895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46896. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46897. __decorate([
  46898. BABYLON.serialize(),
  46899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46900. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46901. __decorate([
  46902. BABYLON.serialize(),
  46903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46904. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46905. __decorate([
  46906. BABYLON.serialize(),
  46907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46908. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46909. __decorate([
  46910. BABYLON.serialize(),
  46911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46912. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46913. __decorate([
  46914. BABYLON.serialize(),
  46915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46916. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46917. __decorate([
  46918. BABYLON.serialize(),
  46919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46920. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46921. __decorate([
  46922. BABYLON.serialize(),
  46923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46924. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46925. __decorate([
  46926. BABYLON.serialize(),
  46927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46928. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46929. __decorate([
  46930. BABYLON.serialize(),
  46931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46932. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46933. __decorate([
  46934. BABYLON.serialize(),
  46935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46936. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46937. __decorate([
  46938. BABYLON.serialize(),
  46939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46940. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46941. __decorate([
  46942. BABYLON.serialize(),
  46943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46944. ], PBRMaterial.prototype, "useParallax", void 0);
  46945. __decorate([
  46946. BABYLON.serialize(),
  46947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46948. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46949. __decorate([
  46950. BABYLON.serialize(),
  46951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46952. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46953. __decorate([
  46954. BABYLON.serialize(),
  46955. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46956. ], PBRMaterial.prototype, "disableLighting", void 0);
  46957. __decorate([
  46958. BABYLON.serialize(),
  46959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46960. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46961. __decorate([
  46962. BABYLON.serialize(),
  46963. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46964. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46965. __decorate([
  46966. BABYLON.serialize(),
  46967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46968. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46969. __decorate([
  46970. BABYLON.serialize(),
  46971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46972. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46973. __decorate([
  46974. BABYLON.serialize(),
  46975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46976. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46977. __decorate([
  46978. BABYLON.serialize(),
  46979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46980. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46981. __decorate([
  46982. BABYLON.serialize(),
  46983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46984. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46985. __decorate([
  46986. BABYLON.serializeAsTexture(),
  46987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46988. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46989. __decorate([
  46990. BABYLON.serialize(),
  46991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46992. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46993. __decorate([
  46994. BABYLON.serialize(),
  46995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46996. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46997. __decorate([
  46998. BABYLON.serialize(),
  46999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47000. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47001. __decorate([
  47002. BABYLON.serialize(),
  47003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47004. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47005. __decorate([
  47006. BABYLON.serialize(),
  47007. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47008. ], PBRMaterial.prototype, "unlit", void 0);
  47009. return PBRMaterial;
  47010. }(BABYLON.PBRBaseMaterial));
  47011. BABYLON.PBRMaterial = PBRMaterial;
  47012. })(BABYLON || (BABYLON = {}));
  47013. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47014. var BABYLON;
  47015. (function (BABYLON) {
  47016. /**
  47017. * The PBR material of BJS following the metal roughness convention.
  47018. *
  47019. * This fits to the PBR convention in the GLTF definition:
  47020. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47021. */
  47022. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47023. __extends(PBRMetallicRoughnessMaterial, _super);
  47024. /**
  47025. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47026. *
  47027. * @param name The material name
  47028. * @param scene The scene the material will be use in.
  47029. */
  47030. function PBRMetallicRoughnessMaterial(name, scene) {
  47031. var _this = _super.call(this, name, scene) || this;
  47032. _this._useRoughnessFromMetallicTextureAlpha = false;
  47033. _this._useRoughnessFromMetallicTextureGreen = true;
  47034. _this._useMetallnessFromMetallicTextureBlue = true;
  47035. _this.metallic = 1.0;
  47036. _this.roughness = 1.0;
  47037. return _this;
  47038. }
  47039. /**
  47040. * Return the currrent class name of the material.
  47041. */
  47042. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47043. return "PBRMetallicRoughnessMaterial";
  47044. };
  47045. /**
  47046. * Return the active textures of the material.
  47047. */
  47048. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47049. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47050. if (this.baseTexture) {
  47051. activeTextures.push(this.baseTexture);
  47052. }
  47053. if (this.metallicRoughnessTexture) {
  47054. activeTextures.push(this.metallicRoughnessTexture);
  47055. }
  47056. return activeTextures;
  47057. };
  47058. /**
  47059. * Checks to see if a texture is used in the material.
  47060. * @param texture - Base texture to use.
  47061. * @returns - Boolean specifying if a texture is used in the material.
  47062. */
  47063. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47064. if (_super.prototype.hasTexture.call(this, texture)) {
  47065. return true;
  47066. }
  47067. if (this.baseTexture === texture) {
  47068. return true;
  47069. }
  47070. if (this.metallicRoughnessTexture === texture) {
  47071. return true;
  47072. }
  47073. return false;
  47074. };
  47075. /**
  47076. * Makes a duplicate of the current material.
  47077. * @param name - name to use for the new material.
  47078. */
  47079. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47080. var _this = this;
  47081. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47082. clone.id = name;
  47083. clone.name = name;
  47084. return clone;
  47085. };
  47086. /**
  47087. * Serialize the material to a parsable JSON object.
  47088. */
  47089. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47090. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47091. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47092. return serializationObject;
  47093. };
  47094. /**
  47095. * Parses a JSON object correponding to the serialize function.
  47096. */
  47097. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47098. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47099. };
  47100. __decorate([
  47101. BABYLON.serializeAsColor3(),
  47102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47103. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47104. __decorate([
  47105. BABYLON.serializeAsTexture(),
  47106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47107. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47108. __decorate([
  47109. BABYLON.serialize(),
  47110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47111. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47112. __decorate([
  47113. BABYLON.serialize(),
  47114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47115. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47116. __decorate([
  47117. BABYLON.serializeAsTexture(),
  47118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47119. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47120. return PBRMetallicRoughnessMaterial;
  47121. }(BABYLON.PBRBaseSimpleMaterial));
  47122. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47123. })(BABYLON || (BABYLON = {}));
  47124. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47125. var BABYLON;
  47126. (function (BABYLON) {
  47127. /**
  47128. * The PBR material of BJS following the specular glossiness convention.
  47129. *
  47130. * This fits to the PBR convention in the GLTF definition:
  47131. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47132. */
  47133. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47134. __extends(PBRSpecularGlossinessMaterial, _super);
  47135. /**
  47136. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47137. *
  47138. * @param name The material name
  47139. * @param scene The scene the material will be use in.
  47140. */
  47141. function PBRSpecularGlossinessMaterial(name, scene) {
  47142. var _this = _super.call(this, name, scene) || this;
  47143. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47144. return _this;
  47145. }
  47146. /**
  47147. * Return the currrent class name of the material.
  47148. */
  47149. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47150. return "PBRSpecularGlossinessMaterial";
  47151. };
  47152. /**
  47153. * Return the active textures of the material.
  47154. */
  47155. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47156. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47157. if (this.diffuseTexture) {
  47158. activeTextures.push(this.diffuseTexture);
  47159. }
  47160. if (this.specularGlossinessTexture) {
  47161. activeTextures.push(this.specularGlossinessTexture);
  47162. }
  47163. return activeTextures;
  47164. };
  47165. /**
  47166. * Checks to see if a texture is used in the material.
  47167. * @param texture - Base texture to use.
  47168. * @returns - Boolean specifying if a texture is used in the material.
  47169. */
  47170. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47171. if (_super.prototype.hasTexture.call(this, texture)) {
  47172. return true;
  47173. }
  47174. if (this.diffuseTexture === texture) {
  47175. return true;
  47176. }
  47177. if (this.specularGlossinessTexture === texture) {
  47178. return true;
  47179. }
  47180. return false;
  47181. };
  47182. /**
  47183. * Makes a duplicate of the current material.
  47184. * @param name - name to use for the new material.
  47185. */
  47186. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47187. var _this = this;
  47188. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47189. clone.id = name;
  47190. clone.name = name;
  47191. return clone;
  47192. };
  47193. /**
  47194. * Serialize the material to a parsable JSON object.
  47195. */
  47196. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47197. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47198. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47199. return serializationObject;
  47200. };
  47201. /**
  47202. * Parses a JSON object correponding to the serialize function.
  47203. */
  47204. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47205. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47206. };
  47207. __decorate([
  47208. BABYLON.serializeAsColor3("diffuse"),
  47209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47210. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47211. __decorate([
  47212. BABYLON.serializeAsTexture(),
  47213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47214. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47215. __decorate([
  47216. BABYLON.serializeAsColor3("specular"),
  47217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47218. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47219. __decorate([
  47220. BABYLON.serialize(),
  47221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47222. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47223. __decorate([
  47224. BABYLON.serializeAsTexture(),
  47225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47226. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47227. return PBRSpecularGlossinessMaterial;
  47228. }(BABYLON.PBRBaseSimpleMaterial));
  47229. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47230. })(BABYLON || (BABYLON = {}));
  47231. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47232. var BABYLON;
  47233. (function (BABYLON) {
  47234. BABYLON.CameraInputTypes = {};
  47235. var CameraInputsManager = /** @class */ (function () {
  47236. function CameraInputsManager(camera) {
  47237. this.attached = {};
  47238. this.camera = camera;
  47239. this.checkInputs = function () { };
  47240. }
  47241. /**
  47242. * Add an input method to a camera.
  47243. * builtin inputs example: camera.inputs.addGamepad();
  47244. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47245. * @param input camera input method
  47246. */
  47247. CameraInputsManager.prototype.add = function (input) {
  47248. var type = input.getSimpleName();
  47249. if (this.attached[type]) {
  47250. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47251. return;
  47252. }
  47253. this.attached[type] = input;
  47254. input.camera = this.camera;
  47255. //for checkInputs, we are dynamically creating a function
  47256. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47257. if (input.checkInputs) {
  47258. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47259. }
  47260. if (this.attachedElement) {
  47261. input.attachControl(this.attachedElement);
  47262. }
  47263. };
  47264. /**
  47265. * Remove a specific input method from a camera
  47266. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47267. * @param inputToRemove camera input method
  47268. */
  47269. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47270. for (var cam in this.attached) {
  47271. var input = this.attached[cam];
  47272. if (input === inputToRemove) {
  47273. input.detachControl(this.attachedElement);
  47274. input.camera = null;
  47275. delete this.attached[cam];
  47276. this.rebuildInputCheck();
  47277. }
  47278. }
  47279. };
  47280. CameraInputsManager.prototype.removeByType = function (inputType) {
  47281. for (var cam in this.attached) {
  47282. var input = this.attached[cam];
  47283. if (input.getClassName() === inputType) {
  47284. input.detachControl(this.attachedElement);
  47285. input.camera = null;
  47286. delete this.attached[cam];
  47287. this.rebuildInputCheck();
  47288. }
  47289. }
  47290. };
  47291. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47292. var current = this.checkInputs;
  47293. return function () {
  47294. current();
  47295. fn();
  47296. };
  47297. };
  47298. CameraInputsManager.prototype.attachInput = function (input) {
  47299. if (this.attachedElement) {
  47300. input.attachControl(this.attachedElement, this.noPreventDefault);
  47301. }
  47302. };
  47303. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47304. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47305. if (this.attachedElement) {
  47306. return;
  47307. }
  47308. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47309. this.attachedElement = element;
  47310. this.noPreventDefault = noPreventDefault;
  47311. for (var cam in this.attached) {
  47312. this.attached[cam].attachControl(element, noPreventDefault);
  47313. }
  47314. };
  47315. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47316. if (disconnect === void 0) { disconnect = false; }
  47317. if (this.attachedElement !== element) {
  47318. return;
  47319. }
  47320. for (var cam in this.attached) {
  47321. this.attached[cam].detachControl(element);
  47322. if (disconnect) {
  47323. this.attached[cam].camera = null;
  47324. }
  47325. }
  47326. this.attachedElement = null;
  47327. };
  47328. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47329. this.checkInputs = function () { };
  47330. for (var cam in this.attached) {
  47331. var input = this.attached[cam];
  47332. if (input.checkInputs) {
  47333. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47334. }
  47335. }
  47336. };
  47337. /**
  47338. * Remove all attached input methods from a camera
  47339. */
  47340. CameraInputsManager.prototype.clear = function () {
  47341. if (this.attachedElement) {
  47342. this.detachElement(this.attachedElement, true);
  47343. }
  47344. this.attached = {};
  47345. this.attachedElement = null;
  47346. this.checkInputs = function () { };
  47347. };
  47348. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47349. var inputs = {};
  47350. for (var cam in this.attached) {
  47351. var input = this.attached[cam];
  47352. var res = BABYLON.SerializationHelper.Serialize(input);
  47353. inputs[input.getClassName()] = res;
  47354. }
  47355. serializedCamera.inputsmgr = inputs;
  47356. };
  47357. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47358. var parsedInputs = parsedCamera.inputsmgr;
  47359. if (parsedInputs) {
  47360. this.clear();
  47361. for (var n in parsedInputs) {
  47362. var construct = BABYLON.CameraInputTypes[n];
  47363. if (construct) {
  47364. var parsedinput = parsedInputs[n];
  47365. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47366. this.add(input);
  47367. }
  47368. }
  47369. }
  47370. else {
  47371. //2016-03-08 this part is for managing backward compatibility
  47372. for (var n in this.attached) {
  47373. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47374. if (construct) {
  47375. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47376. this.remove(this.attached[n]);
  47377. this.add(input);
  47378. }
  47379. }
  47380. }
  47381. };
  47382. return CameraInputsManager;
  47383. }());
  47384. BABYLON.CameraInputsManager = CameraInputsManager;
  47385. })(BABYLON || (BABYLON = {}));
  47386. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47387. var BABYLON;
  47388. (function (BABYLON) {
  47389. var TargetCamera = /** @class */ (function (_super) {
  47390. __extends(TargetCamera, _super);
  47391. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47392. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47393. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47394. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47395. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47396. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47397. _this.speed = 2.0;
  47398. _this.noRotationConstraint = false;
  47399. _this.lockedTarget = null;
  47400. _this._currentTarget = BABYLON.Vector3.Zero();
  47401. _this._viewMatrix = BABYLON.Matrix.Zero();
  47402. _this._camMatrix = BABYLON.Matrix.Zero();
  47403. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47404. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47405. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47406. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47407. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47408. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47409. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47410. return _this;
  47411. }
  47412. TargetCamera.prototype.getFrontPosition = function (distance) {
  47413. this.getWorldMatrix();
  47414. var direction = this.getTarget().subtract(this.position);
  47415. direction.normalize();
  47416. direction.scaleInPlace(distance);
  47417. return this.globalPosition.add(direction);
  47418. };
  47419. TargetCamera.prototype._getLockedTargetPosition = function () {
  47420. if (!this.lockedTarget) {
  47421. return null;
  47422. }
  47423. if (this.lockedTarget.absolutePosition) {
  47424. this.lockedTarget.computeWorldMatrix();
  47425. }
  47426. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47427. };
  47428. TargetCamera.prototype.storeState = function () {
  47429. this._storedPosition = this.position.clone();
  47430. this._storedRotation = this.rotation.clone();
  47431. if (this.rotationQuaternion) {
  47432. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47433. }
  47434. return _super.prototype.storeState.call(this);
  47435. };
  47436. /**
  47437. * Restored camera state. You must call storeState() first
  47438. */
  47439. TargetCamera.prototype._restoreStateValues = function () {
  47440. if (!_super.prototype._restoreStateValues.call(this)) {
  47441. return false;
  47442. }
  47443. this.position = this._storedPosition.clone();
  47444. this.rotation = this._storedRotation.clone();
  47445. if (this.rotationQuaternion) {
  47446. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47447. }
  47448. this.cameraDirection.copyFromFloats(0, 0, 0);
  47449. this.cameraRotation.copyFromFloats(0, 0);
  47450. return true;
  47451. };
  47452. // Cache
  47453. TargetCamera.prototype._initCache = function () {
  47454. _super.prototype._initCache.call(this);
  47455. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47456. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47457. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47458. };
  47459. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47460. if (!ignoreParentClass) {
  47461. _super.prototype._updateCache.call(this);
  47462. }
  47463. var lockedTargetPosition = this._getLockedTargetPosition();
  47464. if (!lockedTargetPosition) {
  47465. this._cache.lockedTarget = null;
  47466. }
  47467. else {
  47468. if (!this._cache.lockedTarget) {
  47469. this._cache.lockedTarget = lockedTargetPosition.clone();
  47470. }
  47471. else {
  47472. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47473. }
  47474. }
  47475. this._cache.rotation.copyFrom(this.rotation);
  47476. if (this.rotationQuaternion)
  47477. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47478. };
  47479. // Synchronized
  47480. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47481. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47482. return false;
  47483. }
  47484. var lockedTargetPosition = this._getLockedTargetPosition();
  47485. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47486. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47487. };
  47488. // Methods
  47489. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47490. var engine = this.getEngine();
  47491. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47492. };
  47493. // Target
  47494. TargetCamera.prototype.setTarget = function (target) {
  47495. this.upVector.normalize();
  47496. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47497. this._camMatrix.invert();
  47498. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47499. var vDir = target.subtract(this.position);
  47500. if (vDir.x >= 0.0) {
  47501. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47502. }
  47503. else {
  47504. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47505. }
  47506. this.rotation.z = 0;
  47507. if (isNaN(this.rotation.x)) {
  47508. this.rotation.x = 0;
  47509. }
  47510. if (isNaN(this.rotation.y)) {
  47511. this.rotation.y = 0;
  47512. }
  47513. if (isNaN(this.rotation.z)) {
  47514. this.rotation.z = 0;
  47515. }
  47516. if (this.rotationQuaternion) {
  47517. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47518. }
  47519. };
  47520. /**
  47521. * Return the current target position of the camera. This value is expressed in local space.
  47522. */
  47523. TargetCamera.prototype.getTarget = function () {
  47524. return this._currentTarget;
  47525. };
  47526. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47527. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47528. };
  47529. TargetCamera.prototype._updatePosition = function () {
  47530. if (this.parent) {
  47531. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47532. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47533. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47534. return;
  47535. }
  47536. this.position.addInPlace(this.cameraDirection);
  47537. };
  47538. TargetCamera.prototype._checkInputs = function () {
  47539. var needToMove = this._decideIfNeedsToMove();
  47540. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47541. // Move
  47542. if (needToMove) {
  47543. this._updatePosition();
  47544. }
  47545. // Rotate
  47546. if (needToRotate) {
  47547. this.rotation.x += this.cameraRotation.x;
  47548. this.rotation.y += this.cameraRotation.y;
  47549. //rotate, if quaternion is set and rotation was used
  47550. if (this.rotationQuaternion) {
  47551. var len = this.rotation.lengthSquared();
  47552. if (len) {
  47553. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47554. }
  47555. }
  47556. if (!this.noRotationConstraint) {
  47557. var limit = (Math.PI / 2) * 0.95;
  47558. if (this.rotation.x > limit)
  47559. this.rotation.x = limit;
  47560. if (this.rotation.x < -limit)
  47561. this.rotation.x = -limit;
  47562. }
  47563. }
  47564. // Inertia
  47565. if (needToMove) {
  47566. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47567. this.cameraDirection.x = 0;
  47568. }
  47569. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47570. this.cameraDirection.y = 0;
  47571. }
  47572. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47573. this.cameraDirection.z = 0;
  47574. }
  47575. this.cameraDirection.scaleInPlace(this.inertia);
  47576. }
  47577. if (needToRotate) {
  47578. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47579. this.cameraRotation.x = 0;
  47580. }
  47581. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47582. this.cameraRotation.y = 0;
  47583. }
  47584. this.cameraRotation.scaleInPlace(this.inertia);
  47585. }
  47586. _super.prototype._checkInputs.call(this);
  47587. };
  47588. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47589. if (this.rotationQuaternion) {
  47590. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47591. }
  47592. else {
  47593. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47594. }
  47595. //update the up vector!
  47596. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47597. };
  47598. TargetCamera.prototype._getViewMatrix = function () {
  47599. if (this.lockedTarget) {
  47600. this.setTarget(this._getLockedTargetPosition());
  47601. }
  47602. // Compute
  47603. this._updateCameraRotationMatrix();
  47604. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47605. // Computing target and final matrix
  47606. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47607. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47608. return this._viewMatrix;
  47609. };
  47610. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47611. if (this.parent) {
  47612. var parentWorldMatrix = this.parent.getWorldMatrix();
  47613. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47614. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47615. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47616. this._markSyncedWithParent();
  47617. }
  47618. else {
  47619. this._globalPosition.copyFrom(this.position);
  47620. this._globalCurrentTarget.copyFrom(target);
  47621. this._globalCurrentUpVector.copyFrom(up);
  47622. }
  47623. if (this.getScene().useRightHandedSystem) {
  47624. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47625. }
  47626. else {
  47627. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47628. }
  47629. };
  47630. /**
  47631. * @override
  47632. * Override Camera.createRigCamera
  47633. */
  47634. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47635. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47636. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47637. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47638. if (!this.rotationQuaternion) {
  47639. this.rotationQuaternion = new BABYLON.Quaternion();
  47640. }
  47641. rigCamera._cameraRigParams = {};
  47642. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47643. }
  47644. return rigCamera;
  47645. }
  47646. return null;
  47647. };
  47648. /**
  47649. * @override
  47650. * Override Camera._updateRigCameras
  47651. */
  47652. TargetCamera.prototype._updateRigCameras = function () {
  47653. var camLeft = this._rigCameras[0];
  47654. var camRight = this._rigCameras[1];
  47655. switch (this.cameraRigMode) {
  47656. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47657. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47658. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47660. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47661. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47662. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47663. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47664. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47665. camLeft.setTarget(this.getTarget());
  47666. camRight.setTarget(this.getTarget());
  47667. break;
  47668. case BABYLON.Camera.RIG_MODE_VR:
  47669. if (camLeft.rotationQuaternion) {
  47670. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47671. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47672. }
  47673. else {
  47674. camLeft.rotation.copyFrom(this.rotation);
  47675. camRight.rotation.copyFrom(this.rotation);
  47676. }
  47677. camLeft.position.copyFrom(this.position);
  47678. camRight.position.copyFrom(this.position);
  47679. break;
  47680. }
  47681. _super.prototype._updateRigCameras.call(this);
  47682. };
  47683. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47684. if (!this._rigCamTransformMatrix) {
  47685. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47686. }
  47687. var target = this.getTarget();
  47688. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47689. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47690. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47691. };
  47692. TargetCamera.prototype.getClassName = function () {
  47693. return "TargetCamera";
  47694. };
  47695. __decorate([
  47696. BABYLON.serializeAsVector3()
  47697. ], TargetCamera.prototype, "rotation", void 0);
  47698. __decorate([
  47699. BABYLON.serialize()
  47700. ], TargetCamera.prototype, "speed", void 0);
  47701. __decorate([
  47702. BABYLON.serializeAsMeshReference("lockedTargetId")
  47703. ], TargetCamera.prototype, "lockedTarget", void 0);
  47704. return TargetCamera;
  47705. }(BABYLON.Camera));
  47706. BABYLON.TargetCamera = TargetCamera;
  47707. })(BABYLON || (BABYLON = {}));
  47708. //# sourceMappingURL=babylon.targetCamera.js.map
  47709. var BABYLON;
  47710. (function (BABYLON) {
  47711. var FreeCameraMouseInput = /** @class */ (function () {
  47712. function FreeCameraMouseInput(touchEnabled) {
  47713. if (touchEnabled === void 0) { touchEnabled = true; }
  47714. this.touchEnabled = touchEnabled;
  47715. this.buttons = [0, 1, 2];
  47716. this.angularSensibility = 2000.0;
  47717. this.previousPosition = null;
  47718. }
  47719. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47720. var _this = this;
  47721. var engine = this.camera.getEngine();
  47722. if (!this._pointerInput) {
  47723. this._pointerInput = function (p, s) {
  47724. var evt = p.event;
  47725. if (engine.isInVRExclusivePointerMode) {
  47726. return;
  47727. }
  47728. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47729. return;
  47730. }
  47731. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47732. return;
  47733. }
  47734. var srcElement = (evt.srcElement || evt.target);
  47735. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47736. try {
  47737. srcElement.setPointerCapture(evt.pointerId);
  47738. }
  47739. catch (e) {
  47740. //Nothing to do with the error. Execution will continue.
  47741. }
  47742. _this.previousPosition = {
  47743. x: evt.clientX,
  47744. y: evt.clientY
  47745. };
  47746. if (!noPreventDefault) {
  47747. evt.preventDefault();
  47748. element.focus();
  47749. }
  47750. }
  47751. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47752. try {
  47753. srcElement.releasePointerCapture(evt.pointerId);
  47754. }
  47755. catch (e) {
  47756. //Nothing to do with the error.
  47757. }
  47758. _this.previousPosition = null;
  47759. if (!noPreventDefault) {
  47760. evt.preventDefault();
  47761. }
  47762. }
  47763. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47764. if (!_this.previousPosition || engine.isPointerLock) {
  47765. return;
  47766. }
  47767. var offsetX = evt.clientX - _this.previousPosition.x;
  47768. if (_this.camera.getScene().useRightHandedSystem)
  47769. offsetX *= -1;
  47770. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47771. offsetX *= -1;
  47772. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47773. var offsetY = evt.clientY - _this.previousPosition.y;
  47774. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47775. _this.previousPosition = {
  47776. x: evt.clientX,
  47777. y: evt.clientY
  47778. };
  47779. if (!noPreventDefault) {
  47780. evt.preventDefault();
  47781. }
  47782. }
  47783. };
  47784. }
  47785. this._onMouseMove = function (evt) {
  47786. if (!engine.isPointerLock) {
  47787. return;
  47788. }
  47789. if (engine.isInVRExclusivePointerMode) {
  47790. return;
  47791. }
  47792. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47793. if (_this.camera.getScene().useRightHandedSystem)
  47794. offsetX *= -1;
  47795. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47796. offsetX *= -1;
  47797. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47798. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47799. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47800. _this.previousPosition = null;
  47801. if (!noPreventDefault) {
  47802. evt.preventDefault();
  47803. }
  47804. };
  47805. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47806. element.addEventListener("mousemove", this._onMouseMove, false);
  47807. };
  47808. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47809. if (this._observer && element) {
  47810. this.camera.getScene().onPointerObservable.remove(this._observer);
  47811. if (this._onMouseMove) {
  47812. element.removeEventListener("mousemove", this._onMouseMove);
  47813. }
  47814. this._observer = null;
  47815. this._onMouseMove = null;
  47816. this.previousPosition = null;
  47817. }
  47818. };
  47819. FreeCameraMouseInput.prototype.getClassName = function () {
  47820. return "FreeCameraMouseInput";
  47821. };
  47822. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47823. return "mouse";
  47824. };
  47825. __decorate([
  47826. BABYLON.serialize()
  47827. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47828. __decorate([
  47829. BABYLON.serialize()
  47830. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47831. return FreeCameraMouseInput;
  47832. }());
  47833. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47834. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47835. })(BABYLON || (BABYLON = {}));
  47836. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47837. var BABYLON;
  47838. (function (BABYLON) {
  47839. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47840. function FreeCameraKeyboardMoveInput() {
  47841. this._keys = new Array();
  47842. this.keysUp = [38];
  47843. this.keysDown = [40];
  47844. this.keysLeft = [37];
  47845. this.keysRight = [39];
  47846. }
  47847. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47848. var _this = this;
  47849. if (this._onCanvasBlurObserver) {
  47850. return;
  47851. }
  47852. this._scene = this.camera.getScene();
  47853. this._engine = this._scene.getEngine();
  47854. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47855. _this._keys = [];
  47856. });
  47857. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47858. var evt = info.event;
  47859. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47860. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47861. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47862. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47863. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47864. var index = _this._keys.indexOf(evt.keyCode);
  47865. if (index === -1) {
  47866. _this._keys.push(evt.keyCode);
  47867. }
  47868. if (!noPreventDefault) {
  47869. evt.preventDefault();
  47870. }
  47871. }
  47872. }
  47873. else {
  47874. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47875. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47876. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47877. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47878. var index = _this._keys.indexOf(evt.keyCode);
  47879. if (index >= 0) {
  47880. _this._keys.splice(index, 1);
  47881. }
  47882. if (!noPreventDefault) {
  47883. evt.preventDefault();
  47884. }
  47885. }
  47886. }
  47887. });
  47888. };
  47889. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47890. if (this._scene) {
  47891. if (this._onKeyboardObserver) {
  47892. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47893. }
  47894. if (this._onCanvasBlurObserver) {
  47895. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47896. }
  47897. this._onKeyboardObserver = null;
  47898. this._onCanvasBlurObserver = null;
  47899. }
  47900. this._keys = [];
  47901. };
  47902. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47903. if (this._onKeyboardObserver) {
  47904. var camera = this.camera;
  47905. // Keyboard
  47906. for (var index = 0; index < this._keys.length; index++) {
  47907. var keyCode = this._keys[index];
  47908. var speed = camera._computeLocalCameraSpeed();
  47909. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47910. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47911. }
  47912. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47913. camera._localDirection.copyFromFloats(0, 0, speed);
  47914. }
  47915. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47916. camera._localDirection.copyFromFloats(speed, 0, 0);
  47917. }
  47918. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47919. camera._localDirection.copyFromFloats(0, 0, -speed);
  47920. }
  47921. if (camera.getScene().useRightHandedSystem) {
  47922. camera._localDirection.z *= -1;
  47923. }
  47924. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47925. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47926. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47927. }
  47928. }
  47929. };
  47930. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47931. return "FreeCameraKeyboardMoveInput";
  47932. };
  47933. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47934. this._keys = [];
  47935. };
  47936. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47937. return "keyboard";
  47938. };
  47939. __decorate([
  47940. BABYLON.serialize()
  47941. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47942. __decorate([
  47943. BABYLON.serialize()
  47944. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47945. __decorate([
  47946. BABYLON.serialize()
  47947. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47948. __decorate([
  47949. BABYLON.serialize()
  47950. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47951. return FreeCameraKeyboardMoveInput;
  47952. }());
  47953. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47954. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47955. })(BABYLON || (BABYLON = {}));
  47956. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47957. var BABYLON;
  47958. (function (BABYLON) {
  47959. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47960. __extends(FreeCameraInputsManager, _super);
  47961. function FreeCameraInputsManager(camera) {
  47962. return _super.call(this, camera) || this;
  47963. }
  47964. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47965. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47966. return this;
  47967. };
  47968. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47969. if (touchEnabled === void 0) { touchEnabled = true; }
  47970. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47971. return this;
  47972. };
  47973. FreeCameraInputsManager.prototype.addGamepad = function () {
  47974. this.add(new BABYLON.FreeCameraGamepadInput());
  47975. return this;
  47976. };
  47977. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47978. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47979. return this;
  47980. };
  47981. FreeCameraInputsManager.prototype.addTouch = function () {
  47982. this.add(new BABYLON.FreeCameraTouchInput());
  47983. return this;
  47984. };
  47985. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47986. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47987. return this;
  47988. };
  47989. return FreeCameraInputsManager;
  47990. }(BABYLON.CameraInputsManager));
  47991. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47992. })(BABYLON || (BABYLON = {}));
  47993. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47994. var BABYLON;
  47995. (function (BABYLON) {
  47996. var FreeCamera = /** @class */ (function (_super) {
  47997. __extends(FreeCamera, _super);
  47998. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47999. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48000. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48001. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48002. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48003. _this.checkCollisions = false;
  48004. _this.applyGravity = false;
  48005. _this._needMoveForGravity = false;
  48006. _this._oldPosition = BABYLON.Vector3.Zero();
  48007. _this._diffPosition = BABYLON.Vector3.Zero();
  48008. _this._newPosition = BABYLON.Vector3.Zero();
  48009. // Collisions
  48010. _this._collisionMask = -1;
  48011. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48012. if (collidedMesh === void 0) { collidedMesh = null; }
  48013. //TODO move this to the collision coordinator!
  48014. if (_this.getScene().workerCollisions)
  48015. newPosition.multiplyInPlace(_this._collider._radius);
  48016. var updatePosition = function (newPos) {
  48017. _this._newPosition.copyFrom(newPos);
  48018. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48019. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48020. _this.position.addInPlace(_this._diffPosition);
  48021. if (_this.onCollide && collidedMesh) {
  48022. _this.onCollide(collidedMesh);
  48023. }
  48024. }
  48025. };
  48026. updatePosition(newPosition);
  48027. };
  48028. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48029. _this.inputs.addKeyboard().addMouse();
  48030. return _this;
  48031. }
  48032. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48033. //-- begin properties for backward compatibility for inputs
  48034. /**
  48035. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48036. * Higher values reduce sensitivity.
  48037. */
  48038. get: function () {
  48039. var mouse = this.inputs.attached["mouse"];
  48040. if (mouse)
  48041. return mouse.angularSensibility;
  48042. return 0;
  48043. },
  48044. /**
  48045. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48046. * Higher values reduce sensitivity.
  48047. */
  48048. set: function (value) {
  48049. var mouse = this.inputs.attached["mouse"];
  48050. if (mouse)
  48051. mouse.angularSensibility = value;
  48052. },
  48053. enumerable: true,
  48054. configurable: true
  48055. });
  48056. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48057. get: function () {
  48058. var keyboard = this.inputs.attached["keyboard"];
  48059. if (keyboard)
  48060. return keyboard.keysUp;
  48061. return [];
  48062. },
  48063. set: function (value) {
  48064. var keyboard = this.inputs.attached["keyboard"];
  48065. if (keyboard)
  48066. keyboard.keysUp = value;
  48067. },
  48068. enumerable: true,
  48069. configurable: true
  48070. });
  48071. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48072. get: function () {
  48073. var keyboard = this.inputs.attached["keyboard"];
  48074. if (keyboard)
  48075. return keyboard.keysDown;
  48076. return [];
  48077. },
  48078. set: function (value) {
  48079. var keyboard = this.inputs.attached["keyboard"];
  48080. if (keyboard)
  48081. keyboard.keysDown = value;
  48082. },
  48083. enumerable: true,
  48084. configurable: true
  48085. });
  48086. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48087. get: function () {
  48088. var keyboard = this.inputs.attached["keyboard"];
  48089. if (keyboard)
  48090. return keyboard.keysLeft;
  48091. return [];
  48092. },
  48093. set: function (value) {
  48094. var keyboard = this.inputs.attached["keyboard"];
  48095. if (keyboard)
  48096. keyboard.keysLeft = value;
  48097. },
  48098. enumerable: true,
  48099. configurable: true
  48100. });
  48101. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48102. get: function () {
  48103. var keyboard = this.inputs.attached["keyboard"];
  48104. if (keyboard)
  48105. return keyboard.keysRight;
  48106. return [];
  48107. },
  48108. set: function (value) {
  48109. var keyboard = this.inputs.attached["keyboard"];
  48110. if (keyboard)
  48111. keyboard.keysRight = value;
  48112. },
  48113. enumerable: true,
  48114. configurable: true
  48115. });
  48116. // Controls
  48117. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48118. this.inputs.attachElement(element, noPreventDefault);
  48119. };
  48120. FreeCamera.prototype.detachControl = function (element) {
  48121. this.inputs.detachElement(element);
  48122. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48123. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48124. };
  48125. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48126. get: function () {
  48127. return this._collisionMask;
  48128. },
  48129. set: function (mask) {
  48130. this._collisionMask = !isNaN(mask) ? mask : -1;
  48131. },
  48132. enumerable: true,
  48133. configurable: true
  48134. });
  48135. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48136. var globalPosition;
  48137. if (this.parent) {
  48138. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48139. }
  48140. else {
  48141. globalPosition = this.position;
  48142. }
  48143. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48144. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48145. if (!this._collider) {
  48146. this._collider = new BABYLON.Collider();
  48147. }
  48148. this._collider._radius = this.ellipsoid;
  48149. this._collider.collisionMask = this._collisionMask;
  48150. //no need for clone, as long as gravity is not on.
  48151. var actualDisplacement = displacement;
  48152. //add gravity to the direction to prevent the dual-collision checking
  48153. if (this.applyGravity) {
  48154. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48155. actualDisplacement = displacement.add(this.getScene().gravity);
  48156. }
  48157. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48158. };
  48159. FreeCamera.prototype._checkInputs = function () {
  48160. if (!this._localDirection) {
  48161. this._localDirection = BABYLON.Vector3.Zero();
  48162. this._transformedDirection = BABYLON.Vector3.Zero();
  48163. }
  48164. this.inputs.checkInputs();
  48165. _super.prototype._checkInputs.call(this);
  48166. };
  48167. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48168. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48169. };
  48170. FreeCamera.prototype._updatePosition = function () {
  48171. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48172. this._collideWithWorld(this.cameraDirection);
  48173. }
  48174. else {
  48175. _super.prototype._updatePosition.call(this);
  48176. }
  48177. };
  48178. FreeCamera.prototype.dispose = function () {
  48179. this.inputs.clear();
  48180. _super.prototype.dispose.call(this);
  48181. };
  48182. FreeCamera.prototype.getClassName = function () {
  48183. return "FreeCamera";
  48184. };
  48185. __decorate([
  48186. BABYLON.serializeAsVector3()
  48187. ], FreeCamera.prototype, "ellipsoid", void 0);
  48188. __decorate([
  48189. BABYLON.serializeAsVector3()
  48190. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48191. __decorate([
  48192. BABYLON.serialize()
  48193. ], FreeCamera.prototype, "checkCollisions", void 0);
  48194. __decorate([
  48195. BABYLON.serialize()
  48196. ], FreeCamera.prototype, "applyGravity", void 0);
  48197. return FreeCamera;
  48198. }(BABYLON.TargetCamera));
  48199. BABYLON.FreeCamera = FreeCamera;
  48200. })(BABYLON || (BABYLON = {}));
  48201. //# sourceMappingURL=babylon.freeCamera.js.map
  48202. var BABYLON;
  48203. (function (BABYLON) {
  48204. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48205. function ArcRotateCameraKeyboardMoveInput() {
  48206. this._keys = new Array();
  48207. this.keysUp = [38];
  48208. this.keysDown = [40];
  48209. this.keysLeft = [37];
  48210. this.keysRight = [39];
  48211. this.keysReset = [220];
  48212. this.panningSensibility = 50.0;
  48213. this.zoomingSensibility = 25.0;
  48214. this.useAltToZoom = true;
  48215. }
  48216. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48217. var _this = this;
  48218. if (this._onCanvasBlurObserver) {
  48219. return;
  48220. }
  48221. this._scene = this.camera.getScene();
  48222. this._engine = this._scene.getEngine();
  48223. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48224. _this._keys = [];
  48225. });
  48226. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48227. var evt = info.event;
  48228. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48229. _this._ctrlPressed = evt.ctrlKey;
  48230. _this._altPressed = evt.altKey;
  48231. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48232. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48233. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48234. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48235. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48236. var index = _this._keys.indexOf(evt.keyCode);
  48237. if (index === -1) {
  48238. _this._keys.push(evt.keyCode);
  48239. }
  48240. if (evt.preventDefault) {
  48241. if (!noPreventDefault) {
  48242. evt.preventDefault();
  48243. }
  48244. }
  48245. }
  48246. }
  48247. else {
  48248. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48249. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48250. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48251. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48252. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48253. var index = _this._keys.indexOf(evt.keyCode);
  48254. if (index >= 0) {
  48255. _this._keys.splice(index, 1);
  48256. }
  48257. if (evt.preventDefault) {
  48258. if (!noPreventDefault) {
  48259. evt.preventDefault();
  48260. }
  48261. }
  48262. }
  48263. }
  48264. });
  48265. };
  48266. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48267. if (this._scene) {
  48268. if (this._onKeyboardObserver) {
  48269. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48270. }
  48271. if (this._onCanvasBlurObserver) {
  48272. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48273. }
  48274. this._onKeyboardObserver = null;
  48275. this._onCanvasBlurObserver = null;
  48276. }
  48277. this._keys = [];
  48278. };
  48279. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48280. if (this._onKeyboardObserver) {
  48281. var camera = this.camera;
  48282. for (var index = 0; index < this._keys.length; index++) {
  48283. var keyCode = this._keys[index];
  48284. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48285. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48286. camera.inertialPanningX -= 1 / this.panningSensibility;
  48287. }
  48288. else {
  48289. camera.inertialAlphaOffset -= 0.01;
  48290. }
  48291. }
  48292. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48293. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48294. camera.inertialPanningY += 1 / this.panningSensibility;
  48295. }
  48296. else if (this._altPressed && this.useAltToZoom) {
  48297. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48298. }
  48299. else {
  48300. camera.inertialBetaOffset -= 0.01;
  48301. }
  48302. }
  48303. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48304. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48305. camera.inertialPanningX += 1 / this.panningSensibility;
  48306. }
  48307. else {
  48308. camera.inertialAlphaOffset += 0.01;
  48309. }
  48310. }
  48311. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48312. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48313. camera.inertialPanningY -= 1 / this.panningSensibility;
  48314. }
  48315. else if (this._altPressed && this.useAltToZoom) {
  48316. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48317. }
  48318. else {
  48319. camera.inertialBetaOffset += 0.01;
  48320. }
  48321. }
  48322. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48323. camera.restoreState();
  48324. }
  48325. }
  48326. }
  48327. };
  48328. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48329. return "ArcRotateCameraKeyboardMoveInput";
  48330. };
  48331. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48332. return "keyboard";
  48333. };
  48334. __decorate([
  48335. BABYLON.serialize()
  48336. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48337. __decorate([
  48338. BABYLON.serialize()
  48339. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48340. __decorate([
  48341. BABYLON.serialize()
  48342. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48343. __decorate([
  48344. BABYLON.serialize()
  48345. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48346. __decorate([
  48347. BABYLON.serialize()
  48348. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48349. __decorate([
  48350. BABYLON.serialize()
  48351. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48352. __decorate([
  48353. BABYLON.serialize()
  48354. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48355. __decorate([
  48356. BABYLON.serialize()
  48357. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48358. return ArcRotateCameraKeyboardMoveInput;
  48359. }());
  48360. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48361. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48362. })(BABYLON || (BABYLON = {}));
  48363. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48364. var BABYLON;
  48365. (function (BABYLON) {
  48366. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48367. function ArcRotateCameraMouseWheelInput() {
  48368. this.wheelPrecision = 3.0;
  48369. /**
  48370. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48371. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48372. */
  48373. this.wheelDeltaPercentage = 0;
  48374. }
  48375. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48376. var _this = this;
  48377. this._wheel = function (p, s) {
  48378. //sanity check - this should be a PointerWheel event.
  48379. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48380. return;
  48381. var event = p.event;
  48382. var delta = 0;
  48383. if (event.wheelDelta) {
  48384. if (_this.wheelDeltaPercentage) {
  48385. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48386. if (event.wheelDelta > 0) {
  48387. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48388. }
  48389. else {
  48390. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48391. }
  48392. }
  48393. else {
  48394. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48395. }
  48396. }
  48397. else if (event.detail) {
  48398. delta = -event.detail / _this.wheelPrecision;
  48399. }
  48400. if (delta)
  48401. _this.camera.inertialRadiusOffset += delta;
  48402. if (event.preventDefault) {
  48403. if (!noPreventDefault) {
  48404. event.preventDefault();
  48405. }
  48406. }
  48407. };
  48408. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48409. };
  48410. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48411. if (this._observer && element) {
  48412. this.camera.getScene().onPointerObservable.remove(this._observer);
  48413. this._observer = null;
  48414. this._wheel = null;
  48415. }
  48416. };
  48417. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48418. return "ArcRotateCameraMouseWheelInput";
  48419. };
  48420. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48421. return "mousewheel";
  48422. };
  48423. __decorate([
  48424. BABYLON.serialize()
  48425. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48426. __decorate([
  48427. BABYLON.serialize()
  48428. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48429. return ArcRotateCameraMouseWheelInput;
  48430. }());
  48431. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48432. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48433. })(BABYLON || (BABYLON = {}));
  48434. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48435. var BABYLON;
  48436. (function (BABYLON) {
  48437. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48438. function ArcRotateCameraPointersInput() {
  48439. this.buttons = [0, 1, 2];
  48440. this.angularSensibilityX = 1000.0;
  48441. this.angularSensibilityY = 1000.0;
  48442. this.pinchPrecision = 12.0;
  48443. /**
  48444. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48445. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48446. */
  48447. this.pinchDeltaPercentage = 0;
  48448. this.panningSensibility = 1000.0;
  48449. this.multiTouchPanning = true;
  48450. this.multiTouchPanAndZoom = true;
  48451. this._isPanClick = false;
  48452. this.pinchInwards = true;
  48453. }
  48454. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48455. var _this = this;
  48456. var engine = this.camera.getEngine();
  48457. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48458. var pointA = null;
  48459. var pointB = null;
  48460. var previousPinchSquaredDistance = 0;
  48461. var initialDistance = 0;
  48462. var twoFingerActivityCount = 0;
  48463. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48464. this._pointerInput = function (p, s) {
  48465. var evt = p.event;
  48466. var isTouch = p.event.pointerType === "touch";
  48467. if (engine.isInVRExclusivePointerMode) {
  48468. return;
  48469. }
  48470. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48471. return;
  48472. }
  48473. var srcElement = (evt.srcElement || evt.target);
  48474. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48475. try {
  48476. srcElement.setPointerCapture(evt.pointerId);
  48477. }
  48478. catch (e) {
  48479. //Nothing to do with the error. Execution will continue.
  48480. }
  48481. // Manage panning with pan button click
  48482. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48483. // manage pointers
  48484. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48485. if (pointA === null) {
  48486. pointA = cacheSoloPointer;
  48487. }
  48488. else if (pointB === null) {
  48489. pointB = cacheSoloPointer;
  48490. }
  48491. if (!noPreventDefault) {
  48492. evt.preventDefault();
  48493. element.focus();
  48494. }
  48495. }
  48496. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48497. _this.camera.restoreState();
  48498. }
  48499. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48500. try {
  48501. srcElement.releasePointerCapture(evt.pointerId);
  48502. }
  48503. catch (e) {
  48504. //Nothing to do with the error.
  48505. }
  48506. cacheSoloPointer = null;
  48507. previousPinchSquaredDistance = 0;
  48508. previousMultiTouchPanPosition.isPaning = false;
  48509. previousMultiTouchPanPosition.isPinching = false;
  48510. twoFingerActivityCount = 0;
  48511. initialDistance = 0;
  48512. if (!isTouch) {
  48513. pointB = null; // Mouse and pen are mono pointer
  48514. }
  48515. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48516. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48517. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48518. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48519. if (engine._badOS) {
  48520. pointA = pointB = null;
  48521. }
  48522. else {
  48523. //only remove the impacted pointer in case of multitouch allowing on most
  48524. //platforms switching from rotate to zoom and pan seamlessly.
  48525. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48526. pointA = pointB;
  48527. pointB = null;
  48528. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48529. }
  48530. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48531. pointB = null;
  48532. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48533. }
  48534. else {
  48535. pointA = pointB = null;
  48536. }
  48537. }
  48538. if (!noPreventDefault) {
  48539. evt.preventDefault();
  48540. }
  48541. }
  48542. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48543. if (!noPreventDefault) {
  48544. evt.preventDefault();
  48545. }
  48546. // One button down
  48547. if (pointA && pointB === null && cacheSoloPointer) {
  48548. if (_this.panningSensibility !== 0 &&
  48549. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48550. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48551. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48552. }
  48553. else {
  48554. var offsetX = evt.clientX - cacheSoloPointer.x;
  48555. var offsetY = evt.clientY - cacheSoloPointer.y;
  48556. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48557. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48558. }
  48559. cacheSoloPointer.x = evt.clientX;
  48560. cacheSoloPointer.y = evt.clientY;
  48561. }
  48562. // Two buttons down: pinch/pan
  48563. else if (pointA && pointB) {
  48564. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48565. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48566. ed.x = evt.clientX;
  48567. ed.y = evt.clientY;
  48568. var direction = _this.pinchInwards ? 1 : -1;
  48569. var distX = pointA.x - pointB.x;
  48570. var distY = pointA.y - pointB.y;
  48571. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48572. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48573. if (previousPinchSquaredDistance === 0) {
  48574. initialDistance = pinchDistance;
  48575. previousPinchSquaredDistance = pinchSquaredDistance;
  48576. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48577. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48578. return;
  48579. }
  48580. if (_this.multiTouchPanAndZoom) {
  48581. if (_this.pinchDeltaPercentage) {
  48582. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48583. }
  48584. else {
  48585. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48586. (_this.pinchPrecision *
  48587. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48588. direction);
  48589. }
  48590. if (_this.panningSensibility !== 0) {
  48591. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48592. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48593. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48594. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48595. previousMultiTouchPanPosition.x = pointersCenterX;
  48596. previousMultiTouchPanPosition.y = pointersCenterY;
  48597. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48598. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48599. }
  48600. }
  48601. else {
  48602. twoFingerActivityCount++;
  48603. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48604. if (_this.pinchDeltaPercentage) {
  48605. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48606. }
  48607. else {
  48608. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48609. (_this.pinchPrecision *
  48610. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48611. direction);
  48612. }
  48613. previousMultiTouchPanPosition.isPaning = false;
  48614. previousMultiTouchPanPosition.isPinching = true;
  48615. }
  48616. else {
  48617. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48618. if (!previousMultiTouchPanPosition.isPaning) {
  48619. previousMultiTouchPanPosition.isPaning = true;
  48620. previousMultiTouchPanPosition.isPinching = false;
  48621. previousMultiTouchPanPosition.x = ed.x;
  48622. previousMultiTouchPanPosition.y = ed.y;
  48623. return;
  48624. }
  48625. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48626. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48627. }
  48628. }
  48629. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48630. previousMultiTouchPanPosition.x = ed.x;
  48631. previousMultiTouchPanPosition.y = ed.y;
  48632. }
  48633. }
  48634. previousPinchSquaredDistance = pinchSquaredDistance;
  48635. }
  48636. }
  48637. };
  48638. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48639. this._onContextMenu = function (evt) {
  48640. evt.preventDefault();
  48641. };
  48642. if (!this.camera._useCtrlForPanning) {
  48643. element.addEventListener("contextmenu", this._onContextMenu, false);
  48644. }
  48645. this._onLostFocus = function () {
  48646. //this._keys = [];
  48647. pointA = pointB = null;
  48648. previousPinchSquaredDistance = 0;
  48649. previousMultiTouchPanPosition.isPaning = false;
  48650. previousMultiTouchPanPosition.isPinching = false;
  48651. twoFingerActivityCount = 0;
  48652. cacheSoloPointer = null;
  48653. initialDistance = 0;
  48654. };
  48655. this._onMouseMove = function (evt) {
  48656. if (!engine.isPointerLock) {
  48657. return;
  48658. }
  48659. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48660. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48661. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48662. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48663. if (!noPreventDefault) {
  48664. evt.preventDefault();
  48665. }
  48666. };
  48667. this._onGestureStart = function (e) {
  48668. if (window.MSGesture === undefined) {
  48669. return;
  48670. }
  48671. if (!_this._MSGestureHandler) {
  48672. _this._MSGestureHandler = new MSGesture();
  48673. _this._MSGestureHandler.target = element;
  48674. }
  48675. _this._MSGestureHandler.addPointer(e.pointerId);
  48676. };
  48677. this._onGesture = function (e) {
  48678. _this.camera.radius *= e.scale;
  48679. if (e.preventDefault) {
  48680. if (!noPreventDefault) {
  48681. e.stopPropagation();
  48682. e.preventDefault();
  48683. }
  48684. }
  48685. };
  48686. element.addEventListener("mousemove", this._onMouseMove, false);
  48687. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48688. element.addEventListener("MSGestureChange", this._onGesture, false);
  48689. BABYLON.Tools.RegisterTopRootEvents([
  48690. { name: "blur", handler: this._onLostFocus }
  48691. ]);
  48692. };
  48693. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48694. if (this._onLostFocus) {
  48695. BABYLON.Tools.UnregisterTopRootEvents([
  48696. { name: "blur", handler: this._onLostFocus }
  48697. ]);
  48698. }
  48699. if (element && this._observer) {
  48700. this.camera.getScene().onPointerObservable.remove(this._observer);
  48701. this._observer = null;
  48702. if (this._onContextMenu) {
  48703. element.removeEventListener("contextmenu", this._onContextMenu);
  48704. }
  48705. if (this._onMouseMove) {
  48706. element.removeEventListener("mousemove", this._onMouseMove);
  48707. }
  48708. if (this._onGestureStart) {
  48709. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48710. }
  48711. if (this._onGesture) {
  48712. element.removeEventListener("MSGestureChange", this._onGesture);
  48713. }
  48714. this._isPanClick = false;
  48715. this.pinchInwards = true;
  48716. this._onMouseMove = null;
  48717. this._onGestureStart = null;
  48718. this._onGesture = null;
  48719. this._MSGestureHandler = null;
  48720. this._onLostFocus = null;
  48721. this._onContextMenu = null;
  48722. }
  48723. };
  48724. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48725. return "ArcRotateCameraPointersInput";
  48726. };
  48727. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48728. return "pointers";
  48729. };
  48730. __decorate([
  48731. BABYLON.serialize()
  48732. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48733. __decorate([
  48734. BABYLON.serialize()
  48735. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48736. __decorate([
  48737. BABYLON.serialize()
  48738. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48739. __decorate([
  48740. BABYLON.serialize()
  48741. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48742. __decorate([
  48743. BABYLON.serialize()
  48744. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48745. __decorate([
  48746. BABYLON.serialize()
  48747. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48748. __decorate([
  48749. BABYLON.serialize()
  48750. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48751. __decorate([
  48752. BABYLON.serialize()
  48753. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48754. return ArcRotateCameraPointersInput;
  48755. }());
  48756. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48757. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48758. })(BABYLON || (BABYLON = {}));
  48759. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48760. var BABYLON;
  48761. (function (BABYLON) {
  48762. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48763. __extends(ArcRotateCameraInputsManager, _super);
  48764. function ArcRotateCameraInputsManager(camera) {
  48765. return _super.call(this, camera) || this;
  48766. }
  48767. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48768. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48769. return this;
  48770. };
  48771. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48772. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48773. return this;
  48774. };
  48775. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48776. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48777. return this;
  48778. };
  48779. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48780. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48781. return this;
  48782. };
  48783. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48784. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48785. return this;
  48786. };
  48787. return ArcRotateCameraInputsManager;
  48788. }(BABYLON.CameraInputsManager));
  48789. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48790. })(BABYLON || (BABYLON = {}));
  48791. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48792. var BABYLON;
  48793. (function (BABYLON) {
  48794. var ArcRotateCamera = /** @class */ (function (_super) {
  48795. __extends(ArcRotateCamera, _super);
  48796. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48797. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48798. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48799. _this.inertialAlphaOffset = 0;
  48800. _this.inertialBetaOffset = 0;
  48801. _this.inertialRadiusOffset = 0;
  48802. _this.lowerAlphaLimit = null;
  48803. _this.upperAlphaLimit = null;
  48804. _this.lowerBetaLimit = 0.01;
  48805. _this.upperBetaLimit = Math.PI;
  48806. _this.lowerRadiusLimit = null;
  48807. _this.upperRadiusLimit = null;
  48808. _this.inertialPanningX = 0;
  48809. _this.inertialPanningY = 0;
  48810. _this.pinchToPanMaxDistance = 20;
  48811. _this.panningDistanceLimit = null;
  48812. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48813. _this.panningInertia = 0.9;
  48814. //-- end properties for backward compatibility for inputs
  48815. _this.zoomOnFactor = 1;
  48816. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48817. _this.allowUpsideDown = true;
  48818. _this._viewMatrix = new BABYLON.Matrix();
  48819. // Panning
  48820. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48821. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48822. _this.checkCollisions = false;
  48823. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48824. _this._previousPosition = BABYLON.Vector3.Zero();
  48825. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48826. _this._newPosition = BABYLON.Vector3.Zero();
  48827. _this._computationVector = BABYLON.Vector3.Zero();
  48828. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48829. if (collidedMesh === void 0) { collidedMesh = null; }
  48830. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48831. newPosition.multiplyInPlace(_this._collider._radius);
  48832. }
  48833. if (!collidedMesh) {
  48834. _this._previousPosition.copyFrom(_this.position);
  48835. }
  48836. else {
  48837. _this.setPosition(newPosition);
  48838. if (_this.onCollide) {
  48839. _this.onCollide(collidedMesh);
  48840. }
  48841. }
  48842. // Recompute because of constraints
  48843. var cosa = Math.cos(_this.alpha);
  48844. var sina = Math.sin(_this.alpha);
  48845. var cosb = Math.cos(_this.beta);
  48846. var sinb = Math.sin(_this.beta);
  48847. if (sinb === 0) {
  48848. sinb = 0.0001;
  48849. }
  48850. var target = _this._getTargetPosition();
  48851. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48852. target.addToRef(_this._computationVector, _this._newPosition);
  48853. _this.position.copyFrom(_this._newPosition);
  48854. var up = _this.upVector;
  48855. if (_this.allowUpsideDown && _this.beta < 0) {
  48856. up = up.clone();
  48857. up = up.negate();
  48858. }
  48859. _this._computeViewMatrix(_this.position, target, up);
  48860. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48861. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48862. _this._collisionTriggered = false;
  48863. };
  48864. _this._target = BABYLON.Vector3.Zero();
  48865. if (target) {
  48866. _this.setTarget(target);
  48867. }
  48868. _this.alpha = alpha;
  48869. _this.beta = beta;
  48870. _this.radius = radius;
  48871. _this.getViewMatrix();
  48872. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48873. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48874. return _this;
  48875. }
  48876. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48877. get: function () {
  48878. return this._target;
  48879. },
  48880. set: function (value) {
  48881. this.setTarget(value);
  48882. },
  48883. enumerable: true,
  48884. configurable: true
  48885. });
  48886. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48887. //-- begin properties for backward compatibility for inputs
  48888. get: function () {
  48889. var pointers = this.inputs.attached["pointers"];
  48890. if (pointers)
  48891. return pointers.angularSensibilityX;
  48892. return 0;
  48893. },
  48894. set: function (value) {
  48895. var pointers = this.inputs.attached["pointers"];
  48896. if (pointers) {
  48897. pointers.angularSensibilityX = value;
  48898. }
  48899. },
  48900. enumerable: true,
  48901. configurable: true
  48902. });
  48903. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48904. get: function () {
  48905. var pointers = this.inputs.attached["pointers"];
  48906. if (pointers)
  48907. return pointers.angularSensibilityY;
  48908. return 0;
  48909. },
  48910. set: function (value) {
  48911. var pointers = this.inputs.attached["pointers"];
  48912. if (pointers) {
  48913. pointers.angularSensibilityY = value;
  48914. }
  48915. },
  48916. enumerable: true,
  48917. configurable: true
  48918. });
  48919. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48920. get: function () {
  48921. var pointers = this.inputs.attached["pointers"];
  48922. if (pointers)
  48923. return pointers.pinchPrecision;
  48924. return 0;
  48925. },
  48926. set: function (value) {
  48927. var pointers = this.inputs.attached["pointers"];
  48928. if (pointers) {
  48929. pointers.pinchPrecision = value;
  48930. }
  48931. },
  48932. enumerable: true,
  48933. configurable: true
  48934. });
  48935. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48936. get: function () {
  48937. var pointers = this.inputs.attached["pointers"];
  48938. if (pointers)
  48939. return pointers.pinchDeltaPercentage;
  48940. return 0;
  48941. },
  48942. set: function (value) {
  48943. var pointers = this.inputs.attached["pointers"];
  48944. if (pointers) {
  48945. pointers.pinchDeltaPercentage = value;
  48946. }
  48947. },
  48948. enumerable: true,
  48949. configurable: true
  48950. });
  48951. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48952. get: function () {
  48953. var pointers = this.inputs.attached["pointers"];
  48954. if (pointers)
  48955. return pointers.panningSensibility;
  48956. return 0;
  48957. },
  48958. set: function (value) {
  48959. var pointers = this.inputs.attached["pointers"];
  48960. if (pointers) {
  48961. pointers.panningSensibility = value;
  48962. }
  48963. },
  48964. enumerable: true,
  48965. configurable: true
  48966. });
  48967. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48968. get: function () {
  48969. var keyboard = this.inputs.attached["keyboard"];
  48970. if (keyboard)
  48971. return keyboard.keysUp;
  48972. return [];
  48973. },
  48974. set: function (value) {
  48975. var keyboard = this.inputs.attached["keyboard"];
  48976. if (keyboard)
  48977. keyboard.keysUp = value;
  48978. },
  48979. enumerable: true,
  48980. configurable: true
  48981. });
  48982. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48983. get: function () {
  48984. var keyboard = this.inputs.attached["keyboard"];
  48985. if (keyboard)
  48986. return keyboard.keysDown;
  48987. return [];
  48988. },
  48989. set: function (value) {
  48990. var keyboard = this.inputs.attached["keyboard"];
  48991. if (keyboard)
  48992. keyboard.keysDown = value;
  48993. },
  48994. enumerable: true,
  48995. configurable: true
  48996. });
  48997. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48998. get: function () {
  48999. var keyboard = this.inputs.attached["keyboard"];
  49000. if (keyboard)
  49001. return keyboard.keysLeft;
  49002. return [];
  49003. },
  49004. set: function (value) {
  49005. var keyboard = this.inputs.attached["keyboard"];
  49006. if (keyboard)
  49007. keyboard.keysLeft = value;
  49008. },
  49009. enumerable: true,
  49010. configurable: true
  49011. });
  49012. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49013. get: function () {
  49014. var keyboard = this.inputs.attached["keyboard"];
  49015. if (keyboard)
  49016. return keyboard.keysRight;
  49017. return [];
  49018. },
  49019. set: function (value) {
  49020. var keyboard = this.inputs.attached["keyboard"];
  49021. if (keyboard)
  49022. keyboard.keysRight = value;
  49023. },
  49024. enumerable: true,
  49025. configurable: true
  49026. });
  49027. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49028. get: function () {
  49029. var mousewheel = this.inputs.attached["mousewheel"];
  49030. if (mousewheel)
  49031. return mousewheel.wheelPrecision;
  49032. return 0;
  49033. },
  49034. set: function (value) {
  49035. var mousewheel = this.inputs.attached["mousewheel"];
  49036. if (mousewheel)
  49037. mousewheel.wheelPrecision = value;
  49038. },
  49039. enumerable: true,
  49040. configurable: true
  49041. });
  49042. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49043. get: function () {
  49044. var mousewheel = this.inputs.attached["mousewheel"];
  49045. if (mousewheel)
  49046. return mousewheel.wheelDeltaPercentage;
  49047. return 0;
  49048. },
  49049. set: function (value) {
  49050. var mousewheel = this.inputs.attached["mousewheel"];
  49051. if (mousewheel)
  49052. mousewheel.wheelDeltaPercentage = value;
  49053. },
  49054. enumerable: true,
  49055. configurable: true
  49056. });
  49057. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49058. get: function () {
  49059. return this._bouncingBehavior;
  49060. },
  49061. enumerable: true,
  49062. configurable: true
  49063. });
  49064. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49065. get: function () {
  49066. return this._bouncingBehavior != null;
  49067. },
  49068. set: function (value) {
  49069. if (value === this.useBouncingBehavior) {
  49070. return;
  49071. }
  49072. if (value) {
  49073. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49074. this.addBehavior(this._bouncingBehavior);
  49075. }
  49076. else if (this._bouncingBehavior) {
  49077. this.removeBehavior(this._bouncingBehavior);
  49078. this._bouncingBehavior = null;
  49079. }
  49080. },
  49081. enumerable: true,
  49082. configurable: true
  49083. });
  49084. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49085. get: function () {
  49086. return this._framingBehavior;
  49087. },
  49088. enumerable: true,
  49089. configurable: true
  49090. });
  49091. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49092. get: function () {
  49093. return this._framingBehavior != null;
  49094. },
  49095. set: function (value) {
  49096. if (value === this.useFramingBehavior) {
  49097. return;
  49098. }
  49099. if (value) {
  49100. this._framingBehavior = new BABYLON.FramingBehavior();
  49101. this.addBehavior(this._framingBehavior);
  49102. }
  49103. else if (this._framingBehavior) {
  49104. this.removeBehavior(this._framingBehavior);
  49105. this._framingBehavior = null;
  49106. }
  49107. },
  49108. enumerable: true,
  49109. configurable: true
  49110. });
  49111. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49112. get: function () {
  49113. return this._autoRotationBehavior;
  49114. },
  49115. enumerable: true,
  49116. configurable: true
  49117. });
  49118. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49119. get: function () {
  49120. return this._autoRotationBehavior != null;
  49121. },
  49122. set: function (value) {
  49123. if (value === this.useAutoRotationBehavior) {
  49124. return;
  49125. }
  49126. if (value) {
  49127. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49128. this.addBehavior(this._autoRotationBehavior);
  49129. }
  49130. else if (this._autoRotationBehavior) {
  49131. this.removeBehavior(this._autoRotationBehavior);
  49132. this._autoRotationBehavior = null;
  49133. }
  49134. },
  49135. enumerable: true,
  49136. configurable: true
  49137. });
  49138. // Cache
  49139. ArcRotateCamera.prototype._initCache = function () {
  49140. _super.prototype._initCache.call(this);
  49141. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49142. this._cache.alpha = undefined;
  49143. this._cache.beta = undefined;
  49144. this._cache.radius = undefined;
  49145. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49146. };
  49147. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49148. if (!ignoreParentClass) {
  49149. _super.prototype._updateCache.call(this);
  49150. }
  49151. this._cache._target.copyFrom(this._getTargetPosition());
  49152. this._cache.alpha = this.alpha;
  49153. this._cache.beta = this.beta;
  49154. this._cache.radius = this.radius;
  49155. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49156. };
  49157. ArcRotateCamera.prototype._getTargetPosition = function () {
  49158. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49159. var pos = this._targetHost.getAbsolutePosition();
  49160. if (this._targetBoundingCenter) {
  49161. pos.addToRef(this._targetBoundingCenter, this._target);
  49162. }
  49163. else {
  49164. this._target.copyFrom(pos);
  49165. }
  49166. }
  49167. var lockedTargetPosition = this._getLockedTargetPosition();
  49168. if (lockedTargetPosition) {
  49169. return lockedTargetPosition;
  49170. }
  49171. return this._target;
  49172. };
  49173. ArcRotateCamera.prototype.storeState = function () {
  49174. this._storedAlpha = this.alpha;
  49175. this._storedBeta = this.beta;
  49176. this._storedRadius = this.radius;
  49177. this._storedTarget = this._getTargetPosition().clone();
  49178. return _super.prototype.storeState.call(this);
  49179. };
  49180. /**
  49181. * Restored camera state. You must call storeState() first
  49182. */
  49183. ArcRotateCamera.prototype._restoreStateValues = function () {
  49184. if (!_super.prototype._restoreStateValues.call(this)) {
  49185. return false;
  49186. }
  49187. this.alpha = this._storedAlpha;
  49188. this.beta = this._storedBeta;
  49189. this.radius = this._storedRadius;
  49190. this.setTarget(this._storedTarget.clone());
  49191. this.inertialAlphaOffset = 0;
  49192. this.inertialBetaOffset = 0;
  49193. this.inertialRadiusOffset = 0;
  49194. this.inertialPanningX = 0;
  49195. this.inertialPanningY = 0;
  49196. return true;
  49197. };
  49198. // Synchronized
  49199. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49200. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49201. return false;
  49202. return this._cache._target.equals(this._getTargetPosition())
  49203. && this._cache.alpha === this.alpha
  49204. && this._cache.beta === this.beta
  49205. && this._cache.radius === this.radius
  49206. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49207. };
  49208. // Methods
  49209. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49210. var _this = this;
  49211. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49212. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49213. this._useCtrlForPanning = useCtrlForPanning;
  49214. this._panningMouseButton = panningMouseButton;
  49215. this.inputs.attachElement(element, noPreventDefault);
  49216. this._reset = function () {
  49217. _this.inertialAlphaOffset = 0;
  49218. _this.inertialBetaOffset = 0;
  49219. _this.inertialRadiusOffset = 0;
  49220. _this.inertialPanningX = 0;
  49221. _this.inertialPanningY = 0;
  49222. };
  49223. };
  49224. ArcRotateCamera.prototype.detachControl = function (element) {
  49225. this.inputs.detachElement(element);
  49226. if (this._reset) {
  49227. this._reset();
  49228. }
  49229. };
  49230. ArcRotateCamera.prototype._checkInputs = function () {
  49231. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49232. if (this._collisionTriggered) {
  49233. return;
  49234. }
  49235. this.inputs.checkInputs();
  49236. // Inertia
  49237. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49238. var inertialAlphaOffset = this.inertialAlphaOffset;
  49239. if (this.beta <= 0)
  49240. inertialAlphaOffset *= -1;
  49241. if (this.getScene().useRightHandedSystem)
  49242. inertialAlphaOffset *= -1;
  49243. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49244. inertialAlphaOffset *= -1;
  49245. this.alpha += inertialAlphaOffset;
  49246. this.beta += this.inertialBetaOffset;
  49247. this.radius -= this.inertialRadiusOffset;
  49248. this.inertialAlphaOffset *= this.inertia;
  49249. this.inertialBetaOffset *= this.inertia;
  49250. this.inertialRadiusOffset *= this.inertia;
  49251. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49252. this.inertialAlphaOffset = 0;
  49253. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49254. this.inertialBetaOffset = 0;
  49255. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49256. this.inertialRadiusOffset = 0;
  49257. }
  49258. // Panning inertia
  49259. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49260. if (!this._localDirection) {
  49261. this._localDirection = BABYLON.Vector3.Zero();
  49262. this._transformedDirection = BABYLON.Vector3.Zero();
  49263. }
  49264. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49265. this._localDirection.multiplyInPlace(this.panningAxis);
  49266. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49267. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49268. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49269. if (!this.panningAxis.y) {
  49270. this._transformedDirection.y = 0;
  49271. }
  49272. if (!this._targetHost) {
  49273. if (this.panningDistanceLimit) {
  49274. this._transformedDirection.addInPlace(this._target);
  49275. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49276. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49277. this._target.copyFrom(this._transformedDirection);
  49278. }
  49279. }
  49280. else {
  49281. this._target.addInPlace(this._transformedDirection);
  49282. }
  49283. }
  49284. this.inertialPanningX *= this.panningInertia;
  49285. this.inertialPanningY *= this.panningInertia;
  49286. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49287. this.inertialPanningX = 0;
  49288. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49289. this.inertialPanningY = 0;
  49290. }
  49291. // Limits
  49292. this._checkLimits();
  49293. _super.prototype._checkInputs.call(this);
  49294. };
  49295. ArcRotateCamera.prototype._checkLimits = function () {
  49296. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49297. if (this.allowUpsideDown && this.beta > Math.PI) {
  49298. this.beta = this.beta - (2 * Math.PI);
  49299. }
  49300. }
  49301. else {
  49302. if (this.beta < this.lowerBetaLimit) {
  49303. this.beta = this.lowerBetaLimit;
  49304. }
  49305. }
  49306. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49307. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49308. this.beta = this.beta + (2 * Math.PI);
  49309. }
  49310. }
  49311. else {
  49312. if (this.beta > this.upperBetaLimit) {
  49313. this.beta = this.upperBetaLimit;
  49314. }
  49315. }
  49316. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49317. this.alpha = this.lowerAlphaLimit;
  49318. }
  49319. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49320. this.alpha = this.upperAlphaLimit;
  49321. }
  49322. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49323. this.radius = this.lowerRadiusLimit;
  49324. }
  49325. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49326. this.radius = this.upperRadiusLimit;
  49327. }
  49328. };
  49329. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49330. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49331. this.radius = this._computationVector.length();
  49332. if (this.radius === 0) {
  49333. this.radius = 0.0001; // Just to avoid division by zero
  49334. }
  49335. // Alpha
  49336. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49337. if (this._computationVector.z < 0) {
  49338. this.alpha = 2 * Math.PI - this.alpha;
  49339. }
  49340. // Beta
  49341. this.beta = Math.acos(this._computationVector.y / this.radius);
  49342. this._checkLimits();
  49343. };
  49344. ArcRotateCamera.prototype.setPosition = function (position) {
  49345. if (this.position.equals(position)) {
  49346. return;
  49347. }
  49348. this.position.copyFrom(position);
  49349. this.rebuildAnglesAndRadius();
  49350. };
  49351. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49352. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49353. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49354. if (target.getBoundingInfo) {
  49355. if (toBoundingCenter) {
  49356. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49357. }
  49358. else {
  49359. this._targetBoundingCenter = null;
  49360. }
  49361. this._targetHost = target;
  49362. this._target = this._getTargetPosition();
  49363. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49364. }
  49365. else {
  49366. var newTarget = target;
  49367. var currentTarget = this._getTargetPosition();
  49368. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49369. return;
  49370. }
  49371. this._targetHost = null;
  49372. this._target = newTarget;
  49373. this._targetBoundingCenter = null;
  49374. this.onMeshTargetChangedObservable.notifyObservers(null);
  49375. }
  49376. this.rebuildAnglesAndRadius();
  49377. };
  49378. ArcRotateCamera.prototype._getViewMatrix = function () {
  49379. // Compute
  49380. var cosa = Math.cos(this.alpha);
  49381. var sina = Math.sin(this.alpha);
  49382. var cosb = Math.cos(this.beta);
  49383. var sinb = Math.sin(this.beta);
  49384. if (sinb === 0) {
  49385. sinb = 0.0001;
  49386. }
  49387. var target = this._getTargetPosition();
  49388. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49389. target.addToRef(this._computationVector, this._newPosition);
  49390. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49391. if (!this._collider) {
  49392. this._collider = new BABYLON.Collider();
  49393. }
  49394. this._collider._radius = this.collisionRadius;
  49395. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49396. this._collisionTriggered = true;
  49397. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49398. }
  49399. else {
  49400. this.position.copyFrom(this._newPosition);
  49401. var up = this.upVector;
  49402. if (this.allowUpsideDown && sinb < 0) {
  49403. up = up.clone();
  49404. up = up.negate();
  49405. }
  49406. this._computeViewMatrix(this.position, target, up);
  49407. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49408. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49409. }
  49410. this._currentTarget = target;
  49411. return this._viewMatrix;
  49412. };
  49413. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49414. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49415. meshes = meshes || this.getScene().meshes;
  49416. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49417. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49418. this.radius = distance * this.zoomOnFactor;
  49419. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49420. };
  49421. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49422. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49423. var meshesOrMinMaxVector;
  49424. var distance;
  49425. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49426. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49427. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49428. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49429. }
  49430. else { //minMaxVector and distance
  49431. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49432. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49433. distance = minMaxVectorAndDistance.distance;
  49434. }
  49435. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49436. if (!doNotUpdateMaxZ) {
  49437. this.maxZ = distance * 2;
  49438. }
  49439. };
  49440. /**
  49441. * @override
  49442. * Override Camera.createRigCamera
  49443. */
  49444. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49445. var alphaShift = 0;
  49446. switch (this.cameraRigMode) {
  49447. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49448. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49449. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49450. case BABYLON.Camera.RIG_MODE_VR:
  49451. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49452. break;
  49453. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49454. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49455. break;
  49456. }
  49457. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49458. rigCam._cameraRigParams = {};
  49459. return rigCam;
  49460. };
  49461. /**
  49462. * @override
  49463. * Override Camera._updateRigCameras
  49464. */
  49465. ArcRotateCamera.prototype._updateRigCameras = function () {
  49466. var camLeft = this._rigCameras[0];
  49467. var camRight = this._rigCameras[1];
  49468. camLeft.beta = camRight.beta = this.beta;
  49469. camLeft.radius = camRight.radius = this.radius;
  49470. switch (this.cameraRigMode) {
  49471. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49472. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49473. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49474. case BABYLON.Camera.RIG_MODE_VR:
  49475. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49476. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49477. break;
  49478. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49479. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49480. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49481. break;
  49482. }
  49483. _super.prototype._updateRigCameras.call(this);
  49484. };
  49485. ArcRotateCamera.prototype.dispose = function () {
  49486. this.inputs.clear();
  49487. _super.prototype.dispose.call(this);
  49488. };
  49489. ArcRotateCamera.prototype.getClassName = function () {
  49490. return "ArcRotateCamera";
  49491. };
  49492. __decorate([
  49493. BABYLON.serialize()
  49494. ], ArcRotateCamera.prototype, "alpha", void 0);
  49495. __decorate([
  49496. BABYLON.serialize()
  49497. ], ArcRotateCamera.prototype, "beta", void 0);
  49498. __decorate([
  49499. BABYLON.serialize()
  49500. ], ArcRotateCamera.prototype, "radius", void 0);
  49501. __decorate([
  49502. BABYLON.serializeAsVector3("target")
  49503. ], ArcRotateCamera.prototype, "_target", void 0);
  49504. __decorate([
  49505. BABYLON.serialize()
  49506. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49507. __decorate([
  49508. BABYLON.serialize()
  49509. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49510. __decorate([
  49511. BABYLON.serialize()
  49512. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49513. __decorate([
  49514. BABYLON.serialize()
  49515. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49516. __decorate([
  49517. BABYLON.serialize()
  49518. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49519. __decorate([
  49520. BABYLON.serialize()
  49521. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49522. __decorate([
  49523. BABYLON.serialize()
  49524. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49525. __decorate([
  49526. BABYLON.serialize()
  49527. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49528. __decorate([
  49529. BABYLON.serialize()
  49530. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49531. __decorate([
  49532. BABYLON.serialize()
  49533. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49534. __decorate([
  49535. BABYLON.serialize()
  49536. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49537. __decorate([
  49538. BABYLON.serialize()
  49539. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49540. __decorate([
  49541. BABYLON.serialize()
  49542. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49543. __decorate([
  49544. BABYLON.serializeAsVector3()
  49545. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49546. __decorate([
  49547. BABYLON.serialize()
  49548. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49549. __decorate([
  49550. BABYLON.serialize()
  49551. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49552. __decorate([
  49553. BABYLON.serialize()
  49554. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49555. return ArcRotateCamera;
  49556. }(BABYLON.TargetCamera));
  49557. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49558. })(BABYLON || (BABYLON = {}));
  49559. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49560. var BABYLON;
  49561. (function (BABYLON) {
  49562. /**
  49563. * The HemisphericLight simulates the ambient environment light,
  49564. * so the passed direction is the light reflection direction, not the incoming direction.
  49565. */
  49566. var HemisphericLight = /** @class */ (function (_super) {
  49567. __extends(HemisphericLight, _super);
  49568. /**
  49569. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49570. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49571. * The HemisphericLight can't cast shadows.
  49572. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49573. * @param name The friendly name of the light
  49574. * @param direction The direction of the light reflection
  49575. * @param scene The scene the light belongs to
  49576. */
  49577. function HemisphericLight(name, direction, scene) {
  49578. var _this = _super.call(this, name, scene) || this;
  49579. /**
  49580. * The groundColor is the light in the opposite direction to the one specified during creation.
  49581. * 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.
  49582. */
  49583. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49584. _this.direction = direction || BABYLON.Vector3.Up();
  49585. return _this;
  49586. }
  49587. HemisphericLight.prototype._buildUniformLayout = function () {
  49588. this._uniformBuffer.addUniform("vLightData", 4);
  49589. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49590. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49591. this._uniformBuffer.addUniform("vLightGround", 3);
  49592. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49593. this._uniformBuffer.addUniform("depthValues", 2);
  49594. this._uniformBuffer.create();
  49595. };
  49596. /**
  49597. * Returns the string "HemisphericLight".
  49598. * @return The class name
  49599. */
  49600. HemisphericLight.prototype.getClassName = function () {
  49601. return "HemisphericLight";
  49602. };
  49603. /**
  49604. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49605. * Returns the updated direction.
  49606. * @param target The target the direction should point to
  49607. * @return The computed direction
  49608. */
  49609. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49610. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49611. return this.direction;
  49612. };
  49613. /**
  49614. * Returns the shadow generator associated to the light.
  49615. * @returns Always null for hemispheric lights because it does not support shadows.
  49616. */
  49617. HemisphericLight.prototype.getShadowGenerator = function () {
  49618. return null;
  49619. };
  49620. /**
  49621. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49622. * @param effect The effect to update
  49623. * @param lightIndex The index of the light in the effect to update
  49624. * @returns The hemispheric light
  49625. */
  49626. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49627. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49628. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49629. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49630. return this;
  49631. };
  49632. /**
  49633. * @hidden internal use only.
  49634. */
  49635. HemisphericLight.prototype._getWorldMatrix = function () {
  49636. if (!this._worldMatrix) {
  49637. this._worldMatrix = BABYLON.Matrix.Identity();
  49638. }
  49639. return this._worldMatrix;
  49640. };
  49641. /**
  49642. * Returns the integer 3.
  49643. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49644. */
  49645. HemisphericLight.prototype.getTypeID = function () {
  49646. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49647. };
  49648. __decorate([
  49649. BABYLON.serializeAsColor3()
  49650. ], HemisphericLight.prototype, "groundColor", void 0);
  49651. __decorate([
  49652. BABYLON.serializeAsVector3()
  49653. ], HemisphericLight.prototype, "direction", void 0);
  49654. return HemisphericLight;
  49655. }(BABYLON.Light));
  49656. BABYLON.HemisphericLight = HemisphericLight;
  49657. })(BABYLON || (BABYLON = {}));
  49658. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49659. var BABYLON;
  49660. (function (BABYLON) {
  49661. /**
  49662. * Base implementation IShadowLight
  49663. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49664. */
  49665. var ShadowLight = /** @class */ (function (_super) {
  49666. __extends(ShadowLight, _super);
  49667. function ShadowLight() {
  49668. var _this = _super !== null && _super.apply(this, arguments) || this;
  49669. _this._needProjectionMatrixCompute = true;
  49670. return _this;
  49671. }
  49672. ShadowLight.prototype._setPosition = function (value) {
  49673. this._position = value;
  49674. };
  49675. Object.defineProperty(ShadowLight.prototype, "position", {
  49676. /**
  49677. * Sets the position the shadow will be casted from. Also use as the light position for both
  49678. * point and spot lights.
  49679. */
  49680. get: function () {
  49681. return this._position;
  49682. },
  49683. /**
  49684. * Sets the position the shadow will be casted from. Also use as the light position for both
  49685. * point and spot lights.
  49686. */
  49687. set: function (value) {
  49688. this._setPosition(value);
  49689. },
  49690. enumerable: true,
  49691. configurable: true
  49692. });
  49693. ShadowLight.prototype._setDirection = function (value) {
  49694. this._direction = value;
  49695. };
  49696. Object.defineProperty(ShadowLight.prototype, "direction", {
  49697. /**
  49698. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49699. * Also use as the light direction on spot and directional lights.
  49700. */
  49701. get: function () {
  49702. return this._direction;
  49703. },
  49704. /**
  49705. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49706. * Also use as the light direction on spot and directional lights.
  49707. */
  49708. set: function (value) {
  49709. this._setDirection(value);
  49710. },
  49711. enumerable: true,
  49712. configurable: true
  49713. });
  49714. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49715. /**
  49716. * Gets the shadow projection clipping minimum z value.
  49717. */
  49718. get: function () {
  49719. return this._shadowMinZ;
  49720. },
  49721. /**
  49722. * Sets the shadow projection clipping minimum z value.
  49723. */
  49724. set: function (value) {
  49725. this._shadowMinZ = value;
  49726. this.forceProjectionMatrixCompute();
  49727. },
  49728. enumerable: true,
  49729. configurable: true
  49730. });
  49731. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49732. /**
  49733. * Sets the shadow projection clipping maximum z value.
  49734. */
  49735. get: function () {
  49736. return this._shadowMaxZ;
  49737. },
  49738. /**
  49739. * Gets the shadow projection clipping maximum z value.
  49740. */
  49741. set: function (value) {
  49742. this._shadowMaxZ = value;
  49743. this.forceProjectionMatrixCompute();
  49744. },
  49745. enumerable: true,
  49746. configurable: true
  49747. });
  49748. /**
  49749. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49750. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49751. */
  49752. ShadowLight.prototype.computeTransformedInformation = function () {
  49753. if (this.parent && this.parent.getWorldMatrix) {
  49754. if (!this.transformedPosition) {
  49755. this.transformedPosition = BABYLON.Vector3.Zero();
  49756. }
  49757. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49758. // In case the direction is present.
  49759. if (this.direction) {
  49760. if (!this.transformedDirection) {
  49761. this.transformedDirection = BABYLON.Vector3.Zero();
  49762. }
  49763. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49764. }
  49765. return true;
  49766. }
  49767. return false;
  49768. };
  49769. /**
  49770. * Return the depth scale used for the shadow map.
  49771. * @returns the depth scale.
  49772. */
  49773. ShadowLight.prototype.getDepthScale = function () {
  49774. return 50.0;
  49775. };
  49776. /**
  49777. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49778. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49779. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49780. */
  49781. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49782. return this.transformedDirection ? this.transformedDirection : this.direction;
  49783. };
  49784. /**
  49785. * Returns the ShadowLight absolute position in the World.
  49786. * @returns the position vector in world space
  49787. */
  49788. ShadowLight.prototype.getAbsolutePosition = function () {
  49789. return this.transformedPosition ? this.transformedPosition : this.position;
  49790. };
  49791. /**
  49792. * Sets the ShadowLight direction toward the passed target.
  49793. * @param target The point tot target in local space
  49794. * @returns the updated ShadowLight direction
  49795. */
  49796. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49797. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49798. return this.direction;
  49799. };
  49800. /**
  49801. * Returns the light rotation in euler definition.
  49802. * @returns the x y z rotation in local space.
  49803. */
  49804. ShadowLight.prototype.getRotation = function () {
  49805. this.direction.normalize();
  49806. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49807. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49808. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49809. };
  49810. /**
  49811. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49812. * @returns true if a cube texture needs to be use
  49813. */
  49814. ShadowLight.prototype.needCube = function () {
  49815. return false;
  49816. };
  49817. /**
  49818. * Detects if the projection matrix requires to be recomputed this frame.
  49819. * @returns true if it requires to be recomputed otherwise, false.
  49820. */
  49821. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49822. return this._needProjectionMatrixCompute;
  49823. };
  49824. /**
  49825. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49826. */
  49827. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49828. this._needProjectionMatrixCompute = true;
  49829. };
  49830. /**
  49831. * Get the world matrix of the sahdow lights.
  49832. * @hidden Internal Use Only
  49833. */
  49834. ShadowLight.prototype._getWorldMatrix = function () {
  49835. if (!this._worldMatrix) {
  49836. this._worldMatrix = BABYLON.Matrix.Identity();
  49837. }
  49838. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49839. return this._worldMatrix;
  49840. };
  49841. /**
  49842. * Gets the minZ used for shadow according to both the scene and the light.
  49843. * @param activeCamera The camera we are returning the min for
  49844. * @returns the depth min z
  49845. */
  49846. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49847. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49848. };
  49849. /**
  49850. * Gets the maxZ used for shadow according to both the scene and the light.
  49851. * @param activeCamera The camera we are returning the max for
  49852. * @returns the depth max z
  49853. */
  49854. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49855. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49856. };
  49857. /**
  49858. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49859. * @param matrix The materix to updated with the projection information
  49860. * @param viewMatrix The transform matrix of the light
  49861. * @param renderList The list of mesh to render in the map
  49862. * @returns The current light
  49863. */
  49864. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49865. if (this.customProjectionMatrixBuilder) {
  49866. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49867. }
  49868. else {
  49869. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49870. }
  49871. return this;
  49872. };
  49873. __decorate([
  49874. BABYLON.serializeAsVector3()
  49875. ], ShadowLight.prototype, "position", null);
  49876. __decorate([
  49877. BABYLON.serializeAsVector3()
  49878. ], ShadowLight.prototype, "direction", null);
  49879. __decorate([
  49880. BABYLON.serialize()
  49881. ], ShadowLight.prototype, "shadowMinZ", null);
  49882. __decorate([
  49883. BABYLON.serialize()
  49884. ], ShadowLight.prototype, "shadowMaxZ", null);
  49885. return ShadowLight;
  49886. }(BABYLON.Light));
  49887. BABYLON.ShadowLight = ShadowLight;
  49888. })(BABYLON || (BABYLON = {}));
  49889. //# sourceMappingURL=babylon.shadowLight.js.map
  49890. var BABYLON;
  49891. (function (BABYLON) {
  49892. /**
  49893. * A point light is a light defined by an unique point in world space.
  49894. * The light is emitted in every direction from this point.
  49895. * A good example of a point light is a standard light bulb.
  49896. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49897. */
  49898. var PointLight = /** @class */ (function (_super) {
  49899. __extends(PointLight, _super);
  49900. /**
  49901. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49902. * A PointLight emits the light in every direction.
  49903. * It can cast shadows.
  49904. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49905. * ```javascript
  49906. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49907. * ```
  49908. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49909. * @param name The light friendly name
  49910. * @param position The position of the point light in the scene
  49911. * @param scene The scene the lights belongs to
  49912. */
  49913. function PointLight(name, position, scene) {
  49914. var _this = _super.call(this, name, scene) || this;
  49915. _this._shadowAngle = Math.PI / 2;
  49916. _this.position = position;
  49917. return _this;
  49918. }
  49919. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49920. /**
  49921. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49922. * This specifies what angle the shadow will use to be created.
  49923. *
  49924. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49925. */
  49926. get: function () {
  49927. return this._shadowAngle;
  49928. },
  49929. /**
  49930. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49931. * This specifies what angle the shadow will use to be created.
  49932. *
  49933. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49934. */
  49935. set: function (value) {
  49936. this._shadowAngle = value;
  49937. this.forceProjectionMatrixCompute();
  49938. },
  49939. enumerable: true,
  49940. configurable: true
  49941. });
  49942. Object.defineProperty(PointLight.prototype, "direction", {
  49943. /**
  49944. * Gets the direction if it has been set.
  49945. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49946. */
  49947. get: function () {
  49948. return this._direction;
  49949. },
  49950. /**
  49951. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49952. */
  49953. set: function (value) {
  49954. var previousNeedCube = this.needCube();
  49955. this._direction = value;
  49956. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49957. this._shadowGenerator.recreateShadowMap();
  49958. }
  49959. },
  49960. enumerable: true,
  49961. configurable: true
  49962. });
  49963. /**
  49964. * Returns the string "PointLight"
  49965. * @returns the class name
  49966. */
  49967. PointLight.prototype.getClassName = function () {
  49968. return "PointLight";
  49969. };
  49970. /**
  49971. * Returns the integer 0.
  49972. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49973. */
  49974. PointLight.prototype.getTypeID = function () {
  49975. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49976. };
  49977. /**
  49978. * Specifies wether or not the shadowmap should be a cube texture.
  49979. * @returns true if the shadowmap needs to be a cube texture.
  49980. */
  49981. PointLight.prototype.needCube = function () {
  49982. return !this.direction;
  49983. };
  49984. /**
  49985. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49986. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49987. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49988. */
  49989. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49990. if (this.direction) {
  49991. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49992. }
  49993. else {
  49994. switch (faceIndex) {
  49995. case 0:
  49996. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49997. case 1:
  49998. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49999. case 2:
  50000. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50001. case 3:
  50002. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50003. case 4:
  50004. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50005. case 5:
  50006. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50007. }
  50008. }
  50009. return BABYLON.Vector3.Zero();
  50010. };
  50011. /**
  50012. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50013. * - fov = PI / 2
  50014. * - aspect ratio : 1.0
  50015. * - z-near and far equal to the active camera minZ and maxZ.
  50016. * Returns the PointLight.
  50017. */
  50018. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50019. var activeCamera = this.getScene().activeCamera;
  50020. if (!activeCamera) {
  50021. return;
  50022. }
  50023. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50024. };
  50025. PointLight.prototype._buildUniformLayout = function () {
  50026. this._uniformBuffer.addUniform("vLightData", 4);
  50027. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50028. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50029. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50030. this._uniformBuffer.addUniform("depthValues", 2);
  50031. this._uniformBuffer.create();
  50032. };
  50033. /**
  50034. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50035. * @param effect The effect to update
  50036. * @param lightIndex The index of the light in the effect to update
  50037. * @returns The point light
  50038. */
  50039. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50040. if (this.computeTransformedInformation()) {
  50041. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50042. return this;
  50043. }
  50044. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50045. return this;
  50046. };
  50047. __decorate([
  50048. BABYLON.serialize()
  50049. ], PointLight.prototype, "shadowAngle", null);
  50050. return PointLight;
  50051. }(BABYLON.ShadowLight));
  50052. BABYLON.PointLight = PointLight;
  50053. })(BABYLON || (BABYLON = {}));
  50054. //# sourceMappingURL=babylon.pointLight.js.map
  50055. var BABYLON;
  50056. (function (BABYLON) {
  50057. /**
  50058. * A directional light is defined by a direction (what a surprise!).
  50059. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50060. * 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.
  50061. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50062. */
  50063. var DirectionalLight = /** @class */ (function (_super) {
  50064. __extends(DirectionalLight, _super);
  50065. /**
  50066. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50067. * The directional light is emitted from everywhere in the given direction.
  50068. * It can cast shawdows.
  50069. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50070. * @param name The friendly name of the light
  50071. * @param direction The direction of the light
  50072. * @param scene The scene the light belongs to
  50073. */
  50074. function DirectionalLight(name, direction, scene) {
  50075. var _this = _super.call(this, name, scene) || this;
  50076. _this._shadowFrustumSize = 0;
  50077. _this._shadowOrthoScale = 0.1;
  50078. /**
  50079. * Automatically compute the projection matrix to best fit (including all the casters)
  50080. * on each frame.
  50081. */
  50082. _this.autoUpdateExtends = true;
  50083. // Cache
  50084. _this._orthoLeft = Number.MAX_VALUE;
  50085. _this._orthoRight = Number.MIN_VALUE;
  50086. _this._orthoTop = Number.MIN_VALUE;
  50087. _this._orthoBottom = Number.MAX_VALUE;
  50088. _this.position = direction.scale(-1.0);
  50089. _this.direction = direction;
  50090. return _this;
  50091. }
  50092. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50093. /**
  50094. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50095. */
  50096. get: function () {
  50097. return this._shadowFrustumSize;
  50098. },
  50099. /**
  50100. * Specifies a fix frustum size for the shadow generation.
  50101. */
  50102. set: function (value) {
  50103. this._shadowFrustumSize = value;
  50104. this.forceProjectionMatrixCompute();
  50105. },
  50106. enumerable: true,
  50107. configurable: true
  50108. });
  50109. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50110. /**
  50111. * Gets the shadow projection scale against the optimal computed one.
  50112. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50113. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50114. */
  50115. get: function () {
  50116. return this._shadowOrthoScale;
  50117. },
  50118. /**
  50119. * Sets the shadow projection scale against the optimal computed one.
  50120. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50121. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50122. */
  50123. set: function (value) {
  50124. this._shadowOrthoScale = value;
  50125. this.forceProjectionMatrixCompute();
  50126. },
  50127. enumerable: true,
  50128. configurable: true
  50129. });
  50130. /**
  50131. * Returns the string "DirectionalLight".
  50132. * @return The class name
  50133. */
  50134. DirectionalLight.prototype.getClassName = function () {
  50135. return "DirectionalLight";
  50136. };
  50137. /**
  50138. * Returns the integer 1.
  50139. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50140. */
  50141. DirectionalLight.prototype.getTypeID = function () {
  50142. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50143. };
  50144. /**
  50145. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50146. * Returns the DirectionalLight Shadow projection matrix.
  50147. */
  50148. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50149. if (this.shadowFrustumSize > 0) {
  50150. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50151. }
  50152. else {
  50153. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50154. }
  50155. };
  50156. /**
  50157. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50158. * Returns the DirectionalLight Shadow projection matrix.
  50159. */
  50160. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50161. var activeCamera = this.getScene().activeCamera;
  50162. if (!activeCamera) {
  50163. return;
  50164. }
  50165. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50166. };
  50167. /**
  50168. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50169. * Returns the DirectionalLight Shadow projection matrix.
  50170. */
  50171. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50172. var activeCamera = this.getScene().activeCamera;
  50173. if (!activeCamera) {
  50174. return;
  50175. }
  50176. // Check extends
  50177. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50178. var tempVector3 = BABYLON.Vector3.Zero();
  50179. this._orthoLeft = Number.MAX_VALUE;
  50180. this._orthoRight = Number.MIN_VALUE;
  50181. this._orthoTop = Number.MIN_VALUE;
  50182. this._orthoBottom = Number.MAX_VALUE;
  50183. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50184. var mesh = renderList[meshIndex];
  50185. if (!mesh) {
  50186. continue;
  50187. }
  50188. var boundingInfo = mesh.getBoundingInfo();
  50189. var boundingBox = boundingInfo.boundingBox;
  50190. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50191. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50192. if (tempVector3.x < this._orthoLeft)
  50193. this._orthoLeft = tempVector3.x;
  50194. if (tempVector3.y < this._orthoBottom)
  50195. this._orthoBottom = tempVector3.y;
  50196. if (tempVector3.x > this._orthoRight)
  50197. this._orthoRight = tempVector3.x;
  50198. if (tempVector3.y > this._orthoTop)
  50199. this._orthoTop = tempVector3.y;
  50200. }
  50201. }
  50202. }
  50203. var xOffset = this._orthoRight - this._orthoLeft;
  50204. var yOffset = this._orthoTop - this._orthoBottom;
  50205. 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);
  50206. };
  50207. DirectionalLight.prototype._buildUniformLayout = function () {
  50208. this._uniformBuffer.addUniform("vLightData", 4);
  50209. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50210. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50211. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50212. this._uniformBuffer.addUniform("depthValues", 2);
  50213. this._uniformBuffer.create();
  50214. };
  50215. /**
  50216. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50217. * @param effect The effect to update
  50218. * @param lightIndex The index of the light in the effect to update
  50219. * @returns The directional light
  50220. */
  50221. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50222. if (this.computeTransformedInformation()) {
  50223. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50224. return this;
  50225. }
  50226. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50227. return this;
  50228. };
  50229. /**
  50230. * Gets the minZ used for shadow according to both the scene and the light.
  50231. *
  50232. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50233. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50234. * @param activeCamera The camera we are returning the min for
  50235. * @returns the depth min z
  50236. */
  50237. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50238. return 1;
  50239. };
  50240. /**
  50241. * Gets the maxZ used for shadow according to both the scene and the light.
  50242. *
  50243. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50244. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50245. * @param activeCamera The camera we are returning the max for
  50246. * @returns the depth max z
  50247. */
  50248. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50249. return 1;
  50250. };
  50251. __decorate([
  50252. BABYLON.serialize()
  50253. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50254. __decorate([
  50255. BABYLON.serialize()
  50256. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50257. __decorate([
  50258. BABYLON.serialize()
  50259. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50260. return DirectionalLight;
  50261. }(BABYLON.ShadowLight));
  50262. BABYLON.DirectionalLight = DirectionalLight;
  50263. })(BABYLON || (BABYLON = {}));
  50264. //# sourceMappingURL=babylon.directionalLight.js.map
  50265. var BABYLON;
  50266. (function (BABYLON) {
  50267. /**
  50268. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50269. * These values define a cone of light starting from the position, emitting toward the direction.
  50270. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50271. * and the exponent defines the speed of the decay of the light with distance (reach).
  50272. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50273. */
  50274. var SpotLight = /** @class */ (function (_super) {
  50275. __extends(SpotLight, _super);
  50276. /**
  50277. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50278. * It can cast shadows.
  50279. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50280. * @param name The light friendly name
  50281. * @param position The position of the spot light in the scene
  50282. * @param direction The direction of the light in the scene
  50283. * @param angle The cone angle of the light in Radians
  50284. * @param exponent The light decay speed with the distance from the emission spot
  50285. * @param scene The scene the lights belongs to
  50286. */
  50287. function SpotLight(name, position, direction, angle, exponent, scene) {
  50288. var _this = _super.call(this, name, scene) || this;
  50289. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50290. _this._projectionTextureLightNear = 1e-6;
  50291. _this._projectionTextureLightFar = 1000.0;
  50292. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50293. _this._projectionTextureViewLightDirty = true;
  50294. _this._projectionTextureProjectionLightDirty = true;
  50295. _this._projectionTextureDirty = true;
  50296. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50297. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50298. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50299. _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);
  50300. _this.position = position;
  50301. _this.direction = direction;
  50302. _this.angle = angle;
  50303. _this.exponent = exponent;
  50304. return _this;
  50305. }
  50306. Object.defineProperty(SpotLight.prototype, "angle", {
  50307. /**
  50308. * Gets the cone angle of the spot light in Radians.
  50309. */
  50310. get: function () {
  50311. return this._angle;
  50312. },
  50313. /**
  50314. * Sets the cone angle of the spot light in Radians.
  50315. */
  50316. set: function (value) {
  50317. this._angle = value;
  50318. this._projectionTextureProjectionLightDirty = true;
  50319. this.forceProjectionMatrixCompute();
  50320. },
  50321. enumerable: true,
  50322. configurable: true
  50323. });
  50324. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50325. /**
  50326. * Allows scaling the angle of the light for shadow generation only.
  50327. */
  50328. get: function () {
  50329. return this._shadowAngleScale;
  50330. },
  50331. /**
  50332. * Allows scaling the angle of the light for shadow generation only.
  50333. */
  50334. set: function (value) {
  50335. this._shadowAngleScale = value;
  50336. this.forceProjectionMatrixCompute();
  50337. },
  50338. enumerable: true,
  50339. configurable: true
  50340. });
  50341. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50342. /**
  50343. * Allows reading the projecton texture
  50344. */
  50345. get: function () {
  50346. return this._projectionTextureMatrix;
  50347. },
  50348. enumerable: true,
  50349. configurable: true
  50350. });
  50351. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50352. /**
  50353. * Gets the near clip of the Spotlight for texture projection.
  50354. */
  50355. get: function () {
  50356. return this._projectionTextureLightNear;
  50357. },
  50358. /**
  50359. * Sets the near clip of the Spotlight for texture projection.
  50360. */
  50361. set: function (value) {
  50362. this._projectionTextureLightNear = value;
  50363. this._projectionTextureProjectionLightDirty = true;
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50369. /**
  50370. * Gets the far clip of the Spotlight for texture projection.
  50371. */
  50372. get: function () {
  50373. return this._projectionTextureLightFar;
  50374. },
  50375. /**
  50376. * Sets the far clip of the Spotlight for texture projection.
  50377. */
  50378. set: function (value) {
  50379. this._projectionTextureLightFar = value;
  50380. this._projectionTextureProjectionLightDirty = true;
  50381. },
  50382. enumerable: true,
  50383. configurable: true
  50384. });
  50385. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50386. /**
  50387. * Gets the Up vector of the Spotlight for texture projection.
  50388. */
  50389. get: function () {
  50390. return this._projectionTextureUpDirection;
  50391. },
  50392. /**
  50393. * Sets the Up vector of the Spotlight for texture projection.
  50394. */
  50395. set: function (value) {
  50396. this._projectionTextureUpDirection = value;
  50397. this._projectionTextureProjectionLightDirty = true;
  50398. },
  50399. enumerable: true,
  50400. configurable: true
  50401. });
  50402. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50403. /**
  50404. * Gets the projection texture of the light.
  50405. */
  50406. get: function () {
  50407. return this._projectionTexture;
  50408. },
  50409. /**
  50410. * Sets the projection texture of the light.
  50411. */
  50412. set: function (value) {
  50413. this._projectionTexture = value;
  50414. this._projectionTextureDirty = true;
  50415. },
  50416. enumerable: true,
  50417. configurable: true
  50418. });
  50419. /**
  50420. * Returns the string "SpotLight".
  50421. * @returns the class name
  50422. */
  50423. SpotLight.prototype.getClassName = function () {
  50424. return "SpotLight";
  50425. };
  50426. /**
  50427. * Returns the integer 2.
  50428. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50429. */
  50430. SpotLight.prototype.getTypeID = function () {
  50431. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50432. };
  50433. /**
  50434. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50435. */
  50436. SpotLight.prototype._setDirection = function (value) {
  50437. _super.prototype._setDirection.call(this, value);
  50438. this._projectionTextureViewLightDirty = true;
  50439. };
  50440. /**
  50441. * Overrides the position setter to recompute the projection texture view light Matrix.
  50442. */
  50443. SpotLight.prototype._setPosition = function (value) {
  50444. _super.prototype._setPosition.call(this, value);
  50445. this._projectionTextureViewLightDirty = true;
  50446. };
  50447. /**
  50448. * 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.
  50449. * Returns the SpotLight.
  50450. */
  50451. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50452. var activeCamera = this.getScene().activeCamera;
  50453. if (!activeCamera) {
  50454. return;
  50455. }
  50456. this._shadowAngleScale = this._shadowAngleScale || 1;
  50457. var angle = this._shadowAngleScale * this._angle;
  50458. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50459. };
  50460. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50461. this._projectionTextureViewLightDirty = false;
  50462. this._projectionTextureDirty = true;
  50463. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50464. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50465. };
  50466. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50467. this._projectionTextureProjectionLightDirty = false;
  50468. this._projectionTextureDirty = true;
  50469. var light_far = this.projectionTextureLightFar;
  50470. var light_near = this.projectionTextureLightNear;
  50471. var P = light_far / (light_far - light_near);
  50472. var Q = -P * light_near;
  50473. var S = 1.0 / Math.tan(this._angle / 2.0);
  50474. var A = 1.0;
  50475. 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);
  50476. };
  50477. /**
  50478. * Main function for light texture projection matrix computing.
  50479. */
  50480. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50481. this._projectionTextureDirty = false;
  50482. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50483. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50484. };
  50485. SpotLight.prototype._buildUniformLayout = function () {
  50486. this._uniformBuffer.addUniform("vLightData", 4);
  50487. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50488. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50489. this._uniformBuffer.addUniform("vLightDirection", 3);
  50490. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50491. this._uniformBuffer.addUniform("depthValues", 2);
  50492. this._uniformBuffer.create();
  50493. };
  50494. /**
  50495. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50496. * @param effect The effect to update
  50497. * @param lightIndex The index of the light in the effect to update
  50498. * @returns The spot light
  50499. */
  50500. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50501. var normalizeDirection;
  50502. if (this.computeTransformedInformation()) {
  50503. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50504. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50505. }
  50506. else {
  50507. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50508. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50509. }
  50510. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50511. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50512. if (this._projectionTextureViewLightDirty) {
  50513. this._computeProjectionTextureViewLightMatrix();
  50514. }
  50515. if (this._projectionTextureProjectionLightDirty) {
  50516. this._computeProjectionTextureProjectionLightMatrix();
  50517. }
  50518. if (this._projectionTextureDirty) {
  50519. this._computeProjectionTextureMatrix();
  50520. }
  50521. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50522. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50523. }
  50524. return this;
  50525. };
  50526. /**
  50527. * Disposes the light and the associated resources.
  50528. */
  50529. SpotLight.prototype.dispose = function () {
  50530. _super.prototype.dispose.call(this);
  50531. if (this._projectionTexture) {
  50532. this._projectionTexture.dispose();
  50533. }
  50534. };
  50535. __decorate([
  50536. BABYLON.serialize()
  50537. ], SpotLight.prototype, "angle", null);
  50538. __decorate([
  50539. BABYLON.serialize()
  50540. ], SpotLight.prototype, "shadowAngleScale", null);
  50541. __decorate([
  50542. BABYLON.serialize()
  50543. ], SpotLight.prototype, "exponent", void 0);
  50544. __decorate([
  50545. BABYLON.serialize()
  50546. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50547. __decorate([
  50548. BABYLON.serialize()
  50549. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50550. __decorate([
  50551. BABYLON.serialize()
  50552. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50553. __decorate([
  50554. BABYLON.serializeAsTexture("projectedLightTexture")
  50555. ], SpotLight.prototype, "_projectionTexture", void 0);
  50556. return SpotLight;
  50557. }(BABYLON.ShadowLight));
  50558. BABYLON.SpotLight = SpotLight;
  50559. })(BABYLON || (BABYLON = {}));
  50560. //# sourceMappingURL=babylon.spotLight.js.map
  50561. var BABYLON;
  50562. (function (BABYLON) {
  50563. /**
  50564. * Class used to override all child animations of a given target
  50565. */
  50566. var AnimationPropertiesOverride = /** @class */ (function () {
  50567. function AnimationPropertiesOverride() {
  50568. /**
  50569. * Gets or sets a value indicating if animation blending must be used
  50570. */
  50571. this.enableBlending = false;
  50572. /**
  50573. * Gets or sets the blending speed to use when enableBlending is true
  50574. */
  50575. this.blendingSpeed = 0.01;
  50576. /**
  50577. * Gets or sets the default loop mode to use
  50578. */
  50579. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50580. }
  50581. return AnimationPropertiesOverride;
  50582. }());
  50583. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50584. })(BABYLON || (BABYLON = {}));
  50585. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50586. var BABYLON;
  50587. (function (BABYLON) {
  50588. /**
  50589. * Represents the range of an animation
  50590. */
  50591. var AnimationRange = /** @class */ (function () {
  50592. /**
  50593. * Initializes the range of an animation
  50594. * @param name The name of the animation range
  50595. * @param from The starting frame of the animation
  50596. * @param to The ending frame of the animation
  50597. */
  50598. function AnimationRange(
  50599. /**The name of the animation range**/
  50600. name,
  50601. /**The starting frame of the animation */
  50602. from,
  50603. /**The ending frame of the animation*/
  50604. to) {
  50605. this.name = name;
  50606. this.from = from;
  50607. this.to = to;
  50608. }
  50609. /**
  50610. * Makes a copy of the animation range
  50611. * @returns A copy of the animation range
  50612. */
  50613. AnimationRange.prototype.clone = function () {
  50614. return new AnimationRange(this.name, this.from, this.to);
  50615. };
  50616. return AnimationRange;
  50617. }());
  50618. BABYLON.AnimationRange = AnimationRange;
  50619. /**
  50620. * Composed of a frame, and an action function
  50621. */
  50622. var AnimationEvent = /** @class */ (function () {
  50623. /**
  50624. * Initializes the animation event
  50625. * @param frame The frame for which the event is triggered
  50626. * @param action The event to perform when triggered
  50627. * @param onlyOnce Specifies if the event should be triggered only once
  50628. */
  50629. function AnimationEvent(
  50630. /** The frame for which the event is triggered **/
  50631. frame,
  50632. /** The event to perform when triggered **/
  50633. action,
  50634. /** Specifies if the event should be triggered only once**/
  50635. onlyOnce) {
  50636. this.frame = frame;
  50637. this.action = action;
  50638. this.onlyOnce = onlyOnce;
  50639. /**
  50640. * Specifies if the animation event is done
  50641. */
  50642. this.isDone = false;
  50643. }
  50644. /** @hidden */
  50645. AnimationEvent.prototype._clone = function () {
  50646. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50647. };
  50648. return AnimationEvent;
  50649. }());
  50650. BABYLON.AnimationEvent = AnimationEvent;
  50651. /**
  50652. * A cursor which tracks a point on a path
  50653. */
  50654. var PathCursor = /** @class */ (function () {
  50655. /**
  50656. * Initializes the path cursor
  50657. * @param path The path to track
  50658. */
  50659. function PathCursor(path) {
  50660. this.path = path;
  50661. /**
  50662. * Stores path cursor callbacks for when an onchange event is triggered
  50663. */
  50664. this._onchange = new Array();
  50665. /**
  50666. * The value of the path cursor
  50667. */
  50668. this.value = 0;
  50669. /**
  50670. * The animation array of the path cursor
  50671. */
  50672. this.animations = new Array();
  50673. }
  50674. /**
  50675. * Gets the cursor point on the path
  50676. * @returns A point on the path cursor at the cursor location
  50677. */
  50678. PathCursor.prototype.getPoint = function () {
  50679. var point = this.path.getPointAtLengthPosition(this.value);
  50680. return new BABYLON.Vector3(point.x, 0, point.y);
  50681. };
  50682. /**
  50683. * Moves the cursor ahead by the step amount
  50684. * @param step The amount to move the cursor forward
  50685. * @returns This path cursor
  50686. */
  50687. PathCursor.prototype.moveAhead = function (step) {
  50688. if (step === void 0) { step = 0.002; }
  50689. this.move(step);
  50690. return this;
  50691. };
  50692. /**
  50693. * Moves the cursor behind by the step amount
  50694. * @param step The amount to move the cursor back
  50695. * @returns This path cursor
  50696. */
  50697. PathCursor.prototype.moveBack = function (step) {
  50698. if (step === void 0) { step = 0.002; }
  50699. this.move(-step);
  50700. return this;
  50701. };
  50702. /**
  50703. * Moves the cursor by the step amount
  50704. * If the step amount is greater than one, an exception is thrown
  50705. * @param step The amount to move the cursor
  50706. * @returns This path cursor
  50707. */
  50708. PathCursor.prototype.move = function (step) {
  50709. if (Math.abs(step) > 1) {
  50710. throw "step size should be less than 1.";
  50711. }
  50712. this.value += step;
  50713. this.ensureLimits();
  50714. this.raiseOnChange();
  50715. return this;
  50716. };
  50717. /**
  50718. * Ensures that the value is limited between zero and one
  50719. * @returns This path cursor
  50720. */
  50721. PathCursor.prototype.ensureLimits = function () {
  50722. while (this.value > 1) {
  50723. this.value -= 1;
  50724. }
  50725. while (this.value < 0) {
  50726. this.value += 1;
  50727. }
  50728. return this;
  50729. };
  50730. /**
  50731. * Runs onchange callbacks on change (used by the animation engine)
  50732. * @returns This path cursor
  50733. */
  50734. PathCursor.prototype.raiseOnChange = function () {
  50735. var _this = this;
  50736. this._onchange.forEach(function (f) { return f(_this); });
  50737. return this;
  50738. };
  50739. /**
  50740. * Executes a function on change
  50741. * @param f A path cursor onchange callback
  50742. * @returns This path cursor
  50743. */
  50744. PathCursor.prototype.onchange = function (f) {
  50745. this._onchange.push(f);
  50746. return this;
  50747. };
  50748. return PathCursor;
  50749. }());
  50750. BABYLON.PathCursor = PathCursor;
  50751. /**
  50752. * Enum for the animation key frame interpolation type
  50753. */
  50754. var AnimationKeyInterpolation;
  50755. (function (AnimationKeyInterpolation) {
  50756. /**
  50757. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50758. */
  50759. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50760. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50761. /**
  50762. * Class used to store any kind of animation
  50763. */
  50764. var Animation = /** @class */ (function () {
  50765. /**
  50766. * Initializes the animation
  50767. * @param name Name of the animation
  50768. * @param targetProperty Property to animate
  50769. * @param framePerSecond The frames per second of the animation
  50770. * @param dataType The data type of the animation
  50771. * @param loopMode The loop mode of the animation
  50772. * @param enableBlendings Specifies if blending should be enabled
  50773. */
  50774. function Animation(
  50775. /**Name of the animation */
  50776. name,
  50777. /**Property to animate */
  50778. targetProperty,
  50779. /**The frames per second of the animation */
  50780. framePerSecond,
  50781. /**The data type of the animation */
  50782. dataType,
  50783. /**The loop mode of the animation */
  50784. loopMode,
  50785. /**Specifies if blending should be enabled */
  50786. enableBlending) {
  50787. this.name = name;
  50788. this.targetProperty = targetProperty;
  50789. this.framePerSecond = framePerSecond;
  50790. this.dataType = dataType;
  50791. this.loopMode = loopMode;
  50792. this.enableBlending = enableBlending;
  50793. /**
  50794. * @hidden Internal use only
  50795. */
  50796. this._runtimeAnimations = new Array();
  50797. /**
  50798. * The set of event that will be linked to this animation
  50799. */
  50800. this._events = new Array();
  50801. /**
  50802. * Stores the blending speed of the animation
  50803. */
  50804. this.blendingSpeed = 0.01;
  50805. /**
  50806. * Stores the animation ranges for the animation
  50807. */
  50808. this._ranges = {};
  50809. this.targetPropertyPath = targetProperty.split(".");
  50810. this.dataType = dataType;
  50811. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50812. }
  50813. /**
  50814. * @hidden Internal use
  50815. */
  50816. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50817. var dataType = undefined;
  50818. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50819. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50820. }
  50821. else if (from instanceof BABYLON.Quaternion) {
  50822. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50823. }
  50824. else if (from instanceof BABYLON.Vector3) {
  50825. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50826. }
  50827. else if (from instanceof BABYLON.Vector2) {
  50828. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50829. }
  50830. else if (from instanceof BABYLON.Color3) {
  50831. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50832. }
  50833. else if (from instanceof BABYLON.Size) {
  50834. dataType = Animation.ANIMATIONTYPE_SIZE;
  50835. }
  50836. if (dataType == undefined) {
  50837. return null;
  50838. }
  50839. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50840. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50841. animation.setKeys(keys);
  50842. if (easingFunction !== undefined) {
  50843. animation.setEasingFunction(easingFunction);
  50844. }
  50845. return animation;
  50846. };
  50847. /**
  50848. * Sets up an animation
  50849. * @param property The property to animate
  50850. * @param animationType The animation type to apply
  50851. * @param framePerSecond The frames per second of the animation
  50852. * @param easingFunction The easing function used in the animation
  50853. * @returns The created animation
  50854. */
  50855. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50856. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50857. animation.setEasingFunction(easingFunction);
  50858. return animation;
  50859. };
  50860. /**
  50861. * Create and start an animation on a node
  50862. * @param name defines the name of the global animation that will be run on all nodes
  50863. * @param node defines the root node where the animation will take place
  50864. * @param targetProperty defines property to animate
  50865. * @param framePerSecond defines the number of frame per second yo use
  50866. * @param totalFrame defines the number of frames in total
  50867. * @param from defines the initial value
  50868. * @param to defines the final value
  50869. * @param loopMode defines which loop mode you want to use (off by default)
  50870. * @param easingFunction defines the easing function to use (linear by default)
  50871. * @param onAnimationEnd defines the callback to call when animation end
  50872. * @returns the animatable created for this animation
  50873. */
  50874. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50875. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50876. if (!animation) {
  50877. return null;
  50878. }
  50879. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50880. };
  50881. /**
  50882. * Create and start an animation on a node and its descendants
  50883. * @param name defines the name of the global animation that will be run on all nodes
  50884. * @param node defines the root node where the animation will take place
  50885. * @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
  50886. * @param targetProperty defines property to animate
  50887. * @param framePerSecond defines the number of frame per second to use
  50888. * @param totalFrame defines the number of frames in total
  50889. * @param from defines the initial value
  50890. * @param to defines the final value
  50891. * @param loopMode defines which loop mode you want to use (off by default)
  50892. * @param easingFunction defines the easing function to use (linear by default)
  50893. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50894. * @returns the list of animatables created for all nodes
  50895. * @example https://www.babylonjs-playground.com/#MH0VLI
  50896. */
  50897. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50898. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50899. if (!animation) {
  50900. return null;
  50901. }
  50902. var scene = node.getScene();
  50903. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50904. };
  50905. /**
  50906. * Creates a new animation, merges it with the existing animations and starts it
  50907. * @param name Name of the animation
  50908. * @param node Node which contains the scene that begins the animations
  50909. * @param targetProperty Specifies which property to animate
  50910. * @param framePerSecond The frames per second of the animation
  50911. * @param totalFrame The total number of frames
  50912. * @param from The frame at the beginning of the animation
  50913. * @param to The frame at the end of the animation
  50914. * @param loopMode Specifies the loop mode of the animation
  50915. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50916. * @param onAnimationEnd Callback to run once the animation is complete
  50917. * @returns Nullable animation
  50918. */
  50919. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50920. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50921. if (!animation) {
  50922. return null;
  50923. }
  50924. node.animations.push(animation);
  50925. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50926. };
  50927. /**
  50928. * Transition property of an host to the target Value
  50929. * @param property The property to transition
  50930. * @param targetValue The target Value of the property
  50931. * @param host The object where the property to animate belongs
  50932. * @param scene Scene used to run the animation
  50933. * @param frameRate Framerate (in frame/s) to use
  50934. * @param transition The transition type we want to use
  50935. * @param duration The duration of the animation, in milliseconds
  50936. * @param onAnimationEnd Callback trigger at the end of the animation
  50937. * @returns Nullable animation
  50938. */
  50939. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50940. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50941. if (duration <= 0) {
  50942. host[property] = targetValue;
  50943. if (onAnimationEnd) {
  50944. onAnimationEnd();
  50945. }
  50946. return null;
  50947. }
  50948. var endFrame = frameRate * (duration / 1000);
  50949. transition.setKeys([{
  50950. frame: 0,
  50951. value: host[property].clone ? host[property].clone() : host[property]
  50952. },
  50953. {
  50954. frame: endFrame,
  50955. value: targetValue
  50956. }]);
  50957. if (!host.animations) {
  50958. host.animations = [];
  50959. }
  50960. host.animations.push(transition);
  50961. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50962. animation.onAnimationEnd = onAnimationEnd;
  50963. return animation;
  50964. };
  50965. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50966. /**
  50967. * Return the array of runtime animations currently using this animation
  50968. */
  50969. get: function () {
  50970. return this._runtimeAnimations;
  50971. },
  50972. enumerable: true,
  50973. configurable: true
  50974. });
  50975. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50976. /**
  50977. * Specifies if any of the runtime animations are currently running
  50978. */
  50979. get: function () {
  50980. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50981. var runtimeAnimation = _a[_i];
  50982. if (!runtimeAnimation.isStopped) {
  50983. return true;
  50984. }
  50985. }
  50986. return false;
  50987. },
  50988. enumerable: true,
  50989. configurable: true
  50990. });
  50991. // Methods
  50992. /**
  50993. * Converts the animation to a string
  50994. * @param fullDetails support for multiple levels of logging within scene loading
  50995. * @returns String form of the animation
  50996. */
  50997. Animation.prototype.toString = function (fullDetails) {
  50998. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50999. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51000. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51001. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51002. if (fullDetails) {
  51003. ret += ", Ranges: {";
  51004. var first = true;
  51005. for (var name in this._ranges) {
  51006. if (first) {
  51007. ret += ", ";
  51008. first = false;
  51009. }
  51010. ret += name;
  51011. }
  51012. ret += "}";
  51013. }
  51014. return ret;
  51015. };
  51016. /**
  51017. * Add an event to this animation
  51018. * @param event Event to add
  51019. */
  51020. Animation.prototype.addEvent = function (event) {
  51021. this._events.push(event);
  51022. };
  51023. /**
  51024. * Remove all events found at the given frame
  51025. * @param frame The frame to remove events from
  51026. */
  51027. Animation.prototype.removeEvents = function (frame) {
  51028. for (var index = 0; index < this._events.length; index++) {
  51029. if (this._events[index].frame === frame) {
  51030. this._events.splice(index, 1);
  51031. index--;
  51032. }
  51033. }
  51034. };
  51035. /**
  51036. * Retrieves all the events from the animation
  51037. * @returns Events from the animation
  51038. */
  51039. Animation.prototype.getEvents = function () {
  51040. return this._events;
  51041. };
  51042. /**
  51043. * Creates an animation range
  51044. * @param name Name of the animation range
  51045. * @param from Starting frame of the animation range
  51046. * @param to Ending frame of the animation
  51047. */
  51048. Animation.prototype.createRange = function (name, from, to) {
  51049. // check name not already in use; could happen for bones after serialized
  51050. if (!this._ranges[name]) {
  51051. this._ranges[name] = new AnimationRange(name, from, to);
  51052. }
  51053. };
  51054. /**
  51055. * Deletes an animation range by name
  51056. * @param name Name of the animation range to delete
  51057. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51058. */
  51059. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51060. if (deleteFrames === void 0) { deleteFrames = true; }
  51061. var range = this._ranges[name];
  51062. if (!range) {
  51063. return;
  51064. }
  51065. if (deleteFrames) {
  51066. var from = range.from;
  51067. var to = range.to;
  51068. // this loop MUST go high to low for multiple splices to work
  51069. for (var key = this._keys.length - 1; key >= 0; key--) {
  51070. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51071. this._keys.splice(key, 1);
  51072. }
  51073. }
  51074. }
  51075. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51076. };
  51077. /**
  51078. * Gets the animation range by name, or null if not defined
  51079. * @param name Name of the animation range
  51080. * @returns Nullable animation range
  51081. */
  51082. Animation.prototype.getRange = function (name) {
  51083. return this._ranges[name];
  51084. };
  51085. /**
  51086. * Gets the key frames from the animation
  51087. * @returns The key frames of the animation
  51088. */
  51089. Animation.prototype.getKeys = function () {
  51090. return this._keys;
  51091. };
  51092. /**
  51093. * Gets the highest frame rate of the animation
  51094. * @returns Highest frame rate of the animation
  51095. */
  51096. Animation.prototype.getHighestFrame = function () {
  51097. var ret = 0;
  51098. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51099. if (ret < this._keys[key].frame) {
  51100. ret = this._keys[key].frame;
  51101. }
  51102. }
  51103. return ret;
  51104. };
  51105. /**
  51106. * Gets the easing function of the animation
  51107. * @returns Easing function of the animation
  51108. */
  51109. Animation.prototype.getEasingFunction = function () {
  51110. return this._easingFunction;
  51111. };
  51112. /**
  51113. * Sets the easing function of the animation
  51114. * @param easingFunction A custom mathematical formula for animation
  51115. */
  51116. Animation.prototype.setEasingFunction = function (easingFunction) {
  51117. this._easingFunction = easingFunction;
  51118. };
  51119. /**
  51120. * Interpolates a scalar linearly
  51121. * @param startValue Start value of the animation curve
  51122. * @param endValue End value of the animation curve
  51123. * @param gradient Scalar amount to interpolate
  51124. * @returns Interpolated scalar value
  51125. */
  51126. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51127. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51128. };
  51129. /**
  51130. * Interpolates a scalar cubically
  51131. * @param startValue Start value of the animation curve
  51132. * @param outTangent End tangent of the animation
  51133. * @param endValue End value of the animation curve
  51134. * @param inTangent Start tangent of the animation curve
  51135. * @param gradient Scalar amount to interpolate
  51136. * @returns Interpolated scalar value
  51137. */
  51138. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51139. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51140. };
  51141. /**
  51142. * Interpolates a quaternion using a spherical linear interpolation
  51143. * @param startValue Start value of the animation curve
  51144. * @param endValue End value of the animation curve
  51145. * @param gradient Scalar amount to interpolate
  51146. * @returns Interpolated quaternion value
  51147. */
  51148. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51149. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51150. };
  51151. /**
  51152. * Interpolates a quaternion cubically
  51153. * @param startValue Start value of the animation curve
  51154. * @param outTangent End tangent of the animation curve
  51155. * @param endValue End value of the animation curve
  51156. * @param inTangent Start tangent of the animation curve
  51157. * @param gradient Scalar amount to interpolate
  51158. * @returns Interpolated quaternion value
  51159. */
  51160. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51161. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51162. };
  51163. /**
  51164. * Interpolates a Vector3 linearl
  51165. * @param startValue Start value of the animation curve
  51166. * @param endValue End value of the animation curve
  51167. * @param gradient Scalar amount to interpolate
  51168. * @returns Interpolated scalar value
  51169. */
  51170. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51171. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51172. };
  51173. /**
  51174. * Interpolates a Vector3 cubically
  51175. * @param startValue Start value of the animation curve
  51176. * @param outTangent End tangent of the animation
  51177. * @param endValue End value of the animation curve
  51178. * @param inTangent Start tangent of the animation curve
  51179. * @param gradient Scalar amount to interpolate
  51180. * @returns InterpolatedVector3 value
  51181. */
  51182. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51183. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51184. };
  51185. /**
  51186. * Interpolates a Vector2 linearly
  51187. * @param startValue Start value of the animation curve
  51188. * @param endValue End value of the animation curve
  51189. * @param gradient Scalar amount to interpolate
  51190. * @returns Interpolated Vector2 value
  51191. */
  51192. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51193. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51194. };
  51195. /**
  51196. * Interpolates a Vector2 cubically
  51197. * @param startValue Start value of the animation curve
  51198. * @param outTangent End tangent of the animation
  51199. * @param endValue End value of the animation curve
  51200. * @param inTangent Start tangent of the animation curve
  51201. * @param gradient Scalar amount to interpolate
  51202. * @returns Interpolated Vector2 value
  51203. */
  51204. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51205. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51206. };
  51207. /**
  51208. * Interpolates a size linearly
  51209. * @param startValue Start value of the animation curve
  51210. * @param endValue End value of the animation curve
  51211. * @param gradient Scalar amount to interpolate
  51212. * @returns Interpolated Size value
  51213. */
  51214. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51215. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51216. };
  51217. /**
  51218. * Interpolates a Color3 linearly
  51219. * @param startValue Start value of the animation curve
  51220. * @param endValue End value of the animation curve
  51221. * @param gradient Scalar amount to interpolate
  51222. * @returns Interpolated Color3 value
  51223. */
  51224. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51225. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51226. };
  51227. /**
  51228. * @hidden Internal use only
  51229. */
  51230. Animation.prototype._getKeyValue = function (value) {
  51231. if (typeof value === "function") {
  51232. return value();
  51233. }
  51234. return value;
  51235. };
  51236. /**
  51237. * @hidden Internal use only
  51238. */
  51239. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51240. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51241. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51242. }
  51243. var keys = this.getKeys();
  51244. // Try to get a hash to find the right key
  51245. 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));
  51246. if (keys[startKeyIndex].frame >= currentFrame) {
  51247. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51248. startKeyIndex--;
  51249. }
  51250. }
  51251. for (var key = startKeyIndex; key < keys.length; key++) {
  51252. var endKey = keys[key + 1];
  51253. if (endKey.frame >= currentFrame) {
  51254. var startKey = keys[key];
  51255. var startValue = this._getKeyValue(startKey.value);
  51256. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51257. return startValue;
  51258. }
  51259. var endValue = this._getKeyValue(endKey.value);
  51260. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51261. var frameDelta = endKey.frame - startKey.frame;
  51262. // gradient : percent of currentFrame between the frame inf and the frame sup
  51263. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51264. // check for easingFunction and correction of gradient
  51265. var easingFunction = this.getEasingFunction();
  51266. if (easingFunction != null) {
  51267. gradient = easingFunction.ease(gradient);
  51268. }
  51269. switch (this.dataType) {
  51270. // Float
  51271. case Animation.ANIMATIONTYPE_FLOAT:
  51272. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51273. switch (loopMode) {
  51274. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51275. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51276. return floatValue;
  51277. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51278. return offsetValue * repeatCount + floatValue;
  51279. }
  51280. break;
  51281. // Quaternion
  51282. case Animation.ANIMATIONTYPE_QUATERNION:
  51283. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51284. switch (loopMode) {
  51285. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51286. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51287. return quatValue;
  51288. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51289. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51290. }
  51291. return quatValue;
  51292. // Vector3
  51293. case Animation.ANIMATIONTYPE_VECTOR3:
  51294. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51295. switch (loopMode) {
  51296. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51297. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51298. return vec3Value;
  51299. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51300. return vec3Value.add(offsetValue.scale(repeatCount));
  51301. }
  51302. // Vector2
  51303. case Animation.ANIMATIONTYPE_VECTOR2:
  51304. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51305. switch (loopMode) {
  51306. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51307. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51308. return vec2Value;
  51309. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51310. return vec2Value.add(offsetValue.scale(repeatCount));
  51311. }
  51312. // Size
  51313. case Animation.ANIMATIONTYPE_SIZE:
  51314. switch (loopMode) {
  51315. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51316. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51317. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51318. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51319. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51320. }
  51321. // Color3
  51322. case Animation.ANIMATIONTYPE_COLOR3:
  51323. switch (loopMode) {
  51324. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51325. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51326. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51327. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51328. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51329. }
  51330. // Matrix
  51331. case Animation.ANIMATIONTYPE_MATRIX:
  51332. switch (loopMode) {
  51333. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51334. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51335. if (Animation.AllowMatricesInterpolation) {
  51336. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51337. }
  51338. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51339. return startValue;
  51340. }
  51341. default:
  51342. break;
  51343. }
  51344. break;
  51345. }
  51346. }
  51347. return this._getKeyValue(keys[keys.length - 1].value);
  51348. };
  51349. /**
  51350. * Defines the function to use to interpolate matrices
  51351. * @param startValue defines the start matrix
  51352. * @param endValue defines the end matrix
  51353. * @param gradient defines the gradient between both matrices
  51354. * @param result defines an optional target matrix where to store the interpolation
  51355. * @returns the interpolated matrix
  51356. */
  51357. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51358. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51359. if (result) {
  51360. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51361. return result;
  51362. }
  51363. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51364. }
  51365. if (result) {
  51366. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51367. return result;
  51368. }
  51369. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51370. };
  51371. /**
  51372. * Makes a copy of the animation
  51373. * @returns Cloned animation
  51374. */
  51375. Animation.prototype.clone = function () {
  51376. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51377. clone.enableBlending = this.enableBlending;
  51378. clone.blendingSpeed = this.blendingSpeed;
  51379. if (this._keys) {
  51380. clone.setKeys(this._keys);
  51381. }
  51382. if (this._ranges) {
  51383. clone._ranges = {};
  51384. for (var name in this._ranges) {
  51385. var range = this._ranges[name];
  51386. if (!range) {
  51387. continue;
  51388. }
  51389. clone._ranges[name] = range.clone();
  51390. }
  51391. }
  51392. return clone;
  51393. };
  51394. /**
  51395. * Sets the key frames of the animation
  51396. * @param values The animation key frames to set
  51397. */
  51398. Animation.prototype.setKeys = function (values) {
  51399. this._keys = values.slice(0);
  51400. };
  51401. /**
  51402. * Serializes the animation to an object
  51403. * @returns Serialized object
  51404. */
  51405. Animation.prototype.serialize = function () {
  51406. var serializationObject = {};
  51407. serializationObject.name = this.name;
  51408. serializationObject.property = this.targetProperty;
  51409. serializationObject.framePerSecond = this.framePerSecond;
  51410. serializationObject.dataType = this.dataType;
  51411. serializationObject.loopBehavior = this.loopMode;
  51412. serializationObject.enableBlending = this.enableBlending;
  51413. serializationObject.blendingSpeed = this.blendingSpeed;
  51414. var dataType = this.dataType;
  51415. serializationObject.keys = [];
  51416. var keys = this.getKeys();
  51417. for (var index = 0; index < keys.length; index++) {
  51418. var animationKey = keys[index];
  51419. var key = {};
  51420. key.frame = animationKey.frame;
  51421. switch (dataType) {
  51422. case Animation.ANIMATIONTYPE_FLOAT:
  51423. key.values = [animationKey.value];
  51424. break;
  51425. case Animation.ANIMATIONTYPE_QUATERNION:
  51426. case Animation.ANIMATIONTYPE_MATRIX:
  51427. case Animation.ANIMATIONTYPE_VECTOR3:
  51428. case Animation.ANIMATIONTYPE_COLOR3:
  51429. key.values = animationKey.value.asArray();
  51430. break;
  51431. }
  51432. serializationObject.keys.push(key);
  51433. }
  51434. serializationObject.ranges = [];
  51435. for (var name in this._ranges) {
  51436. var source = this._ranges[name];
  51437. if (!source) {
  51438. continue;
  51439. }
  51440. var range = {};
  51441. range.name = name;
  51442. range.from = source.from;
  51443. range.to = source.to;
  51444. serializationObject.ranges.push(range);
  51445. }
  51446. return serializationObject;
  51447. };
  51448. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51449. /**
  51450. * Get the float animation type
  51451. */
  51452. get: function () {
  51453. return Animation._ANIMATIONTYPE_FLOAT;
  51454. },
  51455. enumerable: true,
  51456. configurable: true
  51457. });
  51458. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51459. /**
  51460. * Get the Vector3 animation type
  51461. */
  51462. get: function () {
  51463. return Animation._ANIMATIONTYPE_VECTOR3;
  51464. },
  51465. enumerable: true,
  51466. configurable: true
  51467. });
  51468. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51469. /**
  51470. * Get the Vectpr2 animation type
  51471. */
  51472. get: function () {
  51473. return Animation._ANIMATIONTYPE_VECTOR2;
  51474. },
  51475. enumerable: true,
  51476. configurable: true
  51477. });
  51478. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51479. /**
  51480. * Get the Size animation type
  51481. */
  51482. get: function () {
  51483. return Animation._ANIMATIONTYPE_SIZE;
  51484. },
  51485. enumerable: true,
  51486. configurable: true
  51487. });
  51488. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51489. /**
  51490. * Get the Quaternion animation type
  51491. */
  51492. get: function () {
  51493. return Animation._ANIMATIONTYPE_QUATERNION;
  51494. },
  51495. enumerable: true,
  51496. configurable: true
  51497. });
  51498. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51499. /**
  51500. * Get the Matrix animation type
  51501. */
  51502. get: function () {
  51503. return Animation._ANIMATIONTYPE_MATRIX;
  51504. },
  51505. enumerable: true,
  51506. configurable: true
  51507. });
  51508. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51509. /**
  51510. * Get the Color3 animation type
  51511. */
  51512. get: function () {
  51513. return Animation._ANIMATIONTYPE_COLOR3;
  51514. },
  51515. enumerable: true,
  51516. configurable: true
  51517. });
  51518. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51519. /**
  51520. * Get the Relative Loop Mode
  51521. */
  51522. get: function () {
  51523. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51524. },
  51525. enumerable: true,
  51526. configurable: true
  51527. });
  51528. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51529. /**
  51530. * Get the Cycle Loop Mode
  51531. */
  51532. get: function () {
  51533. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51534. },
  51535. enumerable: true,
  51536. configurable: true
  51537. });
  51538. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51539. /**
  51540. * Get the Constant Loop Mode
  51541. */
  51542. get: function () {
  51543. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51544. },
  51545. enumerable: true,
  51546. configurable: true
  51547. });
  51548. /** @hidden */
  51549. Animation._UniversalLerp = function (left, right, amount) {
  51550. var constructor = left.constructor;
  51551. if (constructor.Lerp) { // Lerp supported
  51552. return constructor.Lerp(left, right, amount);
  51553. }
  51554. else if (constructor.Slerp) { // Slerp supported
  51555. return constructor.Slerp(left, right, amount);
  51556. }
  51557. else if (left.toFixed) { // Number
  51558. return left * (1.0 - amount) + amount * right;
  51559. }
  51560. else { // Blending not supported
  51561. return right;
  51562. }
  51563. };
  51564. /**
  51565. * Parses an animation object and creates an animation
  51566. * @param parsedAnimation Parsed animation object
  51567. * @returns Animation object
  51568. */
  51569. Animation.Parse = function (parsedAnimation) {
  51570. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51571. var dataType = parsedAnimation.dataType;
  51572. var keys = [];
  51573. var data;
  51574. var index;
  51575. if (parsedAnimation.enableBlending) {
  51576. animation.enableBlending = parsedAnimation.enableBlending;
  51577. }
  51578. if (parsedAnimation.blendingSpeed) {
  51579. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51580. }
  51581. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51582. var key = parsedAnimation.keys[index];
  51583. var inTangent;
  51584. var outTangent;
  51585. switch (dataType) {
  51586. case Animation.ANIMATIONTYPE_FLOAT:
  51587. data = key.values[0];
  51588. if (key.values.length >= 1) {
  51589. inTangent = key.values[1];
  51590. }
  51591. if (key.values.length >= 2) {
  51592. outTangent = key.values[2];
  51593. }
  51594. break;
  51595. case Animation.ANIMATIONTYPE_QUATERNION:
  51596. data = BABYLON.Quaternion.FromArray(key.values);
  51597. if (key.values.length >= 8) {
  51598. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51599. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51600. inTangent = _inTangent;
  51601. }
  51602. }
  51603. if (key.values.length >= 12) {
  51604. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51605. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51606. outTangent = _outTangent;
  51607. }
  51608. }
  51609. break;
  51610. case Animation.ANIMATIONTYPE_MATRIX:
  51611. data = BABYLON.Matrix.FromArray(key.values);
  51612. break;
  51613. case Animation.ANIMATIONTYPE_COLOR3:
  51614. data = BABYLON.Color3.FromArray(key.values);
  51615. break;
  51616. case Animation.ANIMATIONTYPE_VECTOR3:
  51617. default:
  51618. data = BABYLON.Vector3.FromArray(key.values);
  51619. break;
  51620. }
  51621. var keyData = {};
  51622. keyData.frame = key.frame;
  51623. keyData.value = data;
  51624. if (inTangent != undefined) {
  51625. keyData.inTangent = inTangent;
  51626. }
  51627. if (outTangent != undefined) {
  51628. keyData.outTangent = outTangent;
  51629. }
  51630. keys.push(keyData);
  51631. }
  51632. animation.setKeys(keys);
  51633. if (parsedAnimation.ranges) {
  51634. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51635. data = parsedAnimation.ranges[index];
  51636. animation.createRange(data.name, data.from, data.to);
  51637. }
  51638. }
  51639. return animation;
  51640. };
  51641. /**
  51642. * Appends the serialized animations from the source animations
  51643. * @param source Source containing the animations
  51644. * @param destination Target to store the animations
  51645. */
  51646. Animation.AppendSerializedAnimations = function (source, destination) {
  51647. if (source.animations) {
  51648. destination.animations = [];
  51649. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51650. var animation = source.animations[animationIndex];
  51651. destination.animations.push(animation.serialize());
  51652. }
  51653. }
  51654. };
  51655. /**
  51656. * Use matrix interpolation instead of using direct key value when animating matrices
  51657. */
  51658. Animation.AllowMatricesInterpolation = false;
  51659. /**
  51660. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51661. */
  51662. Animation.AllowMatrixDecomposeForInterpolation = true;
  51663. // Statics
  51664. /**
  51665. * Float animation type
  51666. */
  51667. Animation._ANIMATIONTYPE_FLOAT = 0;
  51668. /**
  51669. * Vector3 animation type
  51670. */
  51671. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51672. /**
  51673. * Quaternion animation type
  51674. */
  51675. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51676. /**
  51677. * Matrix animation type
  51678. */
  51679. Animation._ANIMATIONTYPE_MATRIX = 3;
  51680. /**
  51681. * Color3 animation type
  51682. */
  51683. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51684. /**
  51685. * Vector2 animation type
  51686. */
  51687. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51688. /**
  51689. * Size animation type
  51690. */
  51691. Animation._ANIMATIONTYPE_SIZE = 6;
  51692. /**
  51693. * Relative Loop Mode
  51694. */
  51695. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51696. /**
  51697. * Cycle Loop Mode
  51698. */
  51699. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51700. /**
  51701. * Constant Loop Mode
  51702. */
  51703. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51704. return Animation;
  51705. }());
  51706. BABYLON.Animation = Animation;
  51707. })(BABYLON || (BABYLON = {}));
  51708. //# sourceMappingURL=babylon.animation.js.map
  51709. var BABYLON;
  51710. (function (BABYLON) {
  51711. /**
  51712. * This class defines the direct association between an animation and a target
  51713. */
  51714. var TargetedAnimation = /** @class */ (function () {
  51715. function TargetedAnimation() {
  51716. }
  51717. return TargetedAnimation;
  51718. }());
  51719. BABYLON.TargetedAnimation = TargetedAnimation;
  51720. /**
  51721. * Use this class to create coordinated animations on multiple targets
  51722. */
  51723. var AnimationGroup = /** @class */ (function () {
  51724. function AnimationGroup(name, scene) {
  51725. if (scene === void 0) { scene = null; }
  51726. this.name = name;
  51727. this._targetedAnimations = new Array();
  51728. this._animatables = new Array();
  51729. this._from = Number.MAX_VALUE;
  51730. this._to = -Number.MAX_VALUE;
  51731. this._speedRatio = 1;
  51732. this.onAnimationEndObservable = new BABYLON.Observable();
  51733. /**
  51734. * This observable will notify when all animations have ended.
  51735. */
  51736. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51737. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51738. this._scene.animationGroups.push(this);
  51739. }
  51740. Object.defineProperty(AnimationGroup.prototype, "from", {
  51741. /**
  51742. * Gets the first frame
  51743. */
  51744. get: function () {
  51745. return this._from;
  51746. },
  51747. enumerable: true,
  51748. configurable: true
  51749. });
  51750. Object.defineProperty(AnimationGroup.prototype, "to", {
  51751. /**
  51752. * Gets the last frame
  51753. */
  51754. get: function () {
  51755. return this._to;
  51756. },
  51757. enumerable: true,
  51758. configurable: true
  51759. });
  51760. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51761. /**
  51762. * Define if the animations are started
  51763. */
  51764. get: function () {
  51765. return this._isStarted;
  51766. },
  51767. enumerable: true,
  51768. configurable: true
  51769. });
  51770. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51771. /**
  51772. * Gets or sets the speed ratio to use for all animations
  51773. */
  51774. get: function () {
  51775. return this._speedRatio;
  51776. },
  51777. /**
  51778. * Gets or sets the speed ratio to use for all animations
  51779. */
  51780. set: function (value) {
  51781. if (this._speedRatio === value) {
  51782. return;
  51783. }
  51784. this._speedRatio = value;
  51785. for (var index = 0; index < this._animatables.length; index++) {
  51786. var animatable = this._animatables[index];
  51787. animatable.speedRatio = this._speedRatio;
  51788. }
  51789. },
  51790. enumerable: true,
  51791. configurable: true
  51792. });
  51793. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51794. /**
  51795. * Gets the targeted animations for this animation group
  51796. */
  51797. get: function () {
  51798. return this._targetedAnimations;
  51799. },
  51800. enumerable: true,
  51801. configurable: true
  51802. });
  51803. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51804. /**
  51805. * returning the list of animatables controlled by this animation group.
  51806. */
  51807. get: function () {
  51808. return this._animatables;
  51809. },
  51810. enumerable: true,
  51811. configurable: true
  51812. });
  51813. /**
  51814. * Add an animation (with its target) in the group
  51815. * @param animation defines the animation we want to add
  51816. * @param target defines the target of the animation
  51817. * @returns the {BABYLON.TargetedAnimation} object
  51818. */
  51819. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51820. var targetedAnimation = {
  51821. animation: animation,
  51822. target: target
  51823. };
  51824. var keys = animation.getKeys();
  51825. if (this._from > keys[0].frame) {
  51826. this._from = keys[0].frame;
  51827. }
  51828. if (this._to < keys[keys.length - 1].frame) {
  51829. this._to = keys[keys.length - 1].frame;
  51830. }
  51831. this._targetedAnimations.push(targetedAnimation);
  51832. return targetedAnimation;
  51833. };
  51834. /**
  51835. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51836. * It can add constant keys at begin or end
  51837. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51838. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51839. */
  51840. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51841. if (beginFrame === void 0) { beginFrame = null; }
  51842. if (endFrame === void 0) { endFrame = null; }
  51843. if (beginFrame == null)
  51844. beginFrame = this._from;
  51845. if (endFrame == null)
  51846. endFrame = this._to;
  51847. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51848. var targetedAnimation = this._targetedAnimations[index];
  51849. var keys = targetedAnimation.animation.getKeys();
  51850. var startKey = keys[0];
  51851. var endKey = keys[keys.length - 1];
  51852. if (startKey.frame > beginFrame) {
  51853. var newKey = {
  51854. frame: beginFrame,
  51855. value: startKey.value,
  51856. inTangent: startKey.inTangent,
  51857. outTangent: startKey.outTangent,
  51858. interpolation: startKey.interpolation
  51859. };
  51860. keys.splice(0, 0, newKey);
  51861. }
  51862. if (endKey.frame < endFrame) {
  51863. var newKey = {
  51864. frame: endFrame,
  51865. value: endKey.value,
  51866. inTangent: endKey.outTangent,
  51867. outTangent: endKey.outTangent,
  51868. interpolation: endKey.interpolation
  51869. };
  51870. keys.push(newKey);
  51871. }
  51872. }
  51873. this._from = beginFrame;
  51874. this._to = endFrame;
  51875. return this;
  51876. };
  51877. /**
  51878. * Start all animations on given targets
  51879. * @param loop defines if animations must loop
  51880. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51881. * @param from defines the from key (optional)
  51882. * @param to defines the to key (optional)
  51883. * @returns the current animation group
  51884. */
  51885. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51886. var _this = this;
  51887. if (loop === void 0) { loop = false; }
  51888. if (speedRatio === void 0) { speedRatio = 1; }
  51889. if (this._isStarted || this._targetedAnimations.length === 0) {
  51890. return this;
  51891. }
  51892. var _loop_1 = function (targetedAnimation) {
  51893. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51894. animatable.onAnimationEnd = function () {
  51895. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51896. _this._checkAnimationGroupEnded(animatable);
  51897. };
  51898. this_1._animatables.push(animatable);
  51899. };
  51900. var this_1 = this;
  51901. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51902. var targetedAnimation = _a[_i];
  51903. _loop_1(targetedAnimation);
  51904. }
  51905. this._speedRatio = speedRatio;
  51906. this._isStarted = true;
  51907. return this;
  51908. };
  51909. /**
  51910. * Pause all animations
  51911. */
  51912. AnimationGroup.prototype.pause = function () {
  51913. if (!this._isStarted) {
  51914. return this;
  51915. }
  51916. for (var index = 0; index < this._animatables.length; index++) {
  51917. var animatable = this._animatables[index];
  51918. animatable.pause();
  51919. }
  51920. return this;
  51921. };
  51922. /**
  51923. * Play all animations to initial state
  51924. * This function will start() the animations if they were not started or will restart() them if they were paused
  51925. * @param loop defines if animations must loop
  51926. */
  51927. AnimationGroup.prototype.play = function (loop) {
  51928. // only if all animatables are ready and exist
  51929. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51930. if (loop !== undefined) {
  51931. for (var index = 0; index < this._animatables.length; index++) {
  51932. var animatable = this._animatables[index];
  51933. animatable.loopAnimation = loop;
  51934. }
  51935. }
  51936. this.restart();
  51937. }
  51938. else {
  51939. this.stop();
  51940. this.start(loop, this._speedRatio);
  51941. }
  51942. return this;
  51943. };
  51944. /**
  51945. * Reset all animations to initial state
  51946. */
  51947. AnimationGroup.prototype.reset = function () {
  51948. if (!this._isStarted) {
  51949. return this;
  51950. }
  51951. for (var index = 0; index < this._animatables.length; index++) {
  51952. var animatable = this._animatables[index];
  51953. animatable.reset();
  51954. }
  51955. return this;
  51956. };
  51957. /**
  51958. * Restart animations from key 0
  51959. */
  51960. AnimationGroup.prototype.restart = function () {
  51961. if (!this._isStarted) {
  51962. return this;
  51963. }
  51964. for (var index = 0; index < this._animatables.length; index++) {
  51965. var animatable = this._animatables[index];
  51966. animatable.restart();
  51967. }
  51968. return this;
  51969. };
  51970. /**
  51971. * Stop all animations
  51972. */
  51973. AnimationGroup.prototype.stop = function () {
  51974. if (!this._isStarted) {
  51975. return this;
  51976. }
  51977. for (var index = 0; index < this._animatables.length; index++) {
  51978. var animatable = this._animatables[index];
  51979. animatable.stop();
  51980. }
  51981. this._isStarted = false;
  51982. return this;
  51983. };
  51984. /**
  51985. * Set animation weight for all animatables
  51986. * @param weight defines the weight to use
  51987. * @return the animationGroup
  51988. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51989. */
  51990. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51991. for (var index = 0; index < this._animatables.length; index++) {
  51992. var animatable = this._animatables[index];
  51993. animatable.weight = weight;
  51994. }
  51995. return this;
  51996. };
  51997. /**
  51998. * Synchronize and normalize all animatables with a source animatable
  51999. * @param root defines the root animatable to synchronize with
  52000. * @return the animationGroup
  52001. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52002. */
  52003. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52004. for (var index = 0; index < this._animatables.length; index++) {
  52005. var animatable = this._animatables[index];
  52006. animatable.syncWith(root);
  52007. }
  52008. return this;
  52009. };
  52010. /**
  52011. * Goes to a specific frame in this animation group
  52012. * @param frame the frame number to go to
  52013. * @return the animationGroup
  52014. */
  52015. AnimationGroup.prototype.goToFrame = function (frame) {
  52016. if (!this._isStarted) {
  52017. return this;
  52018. }
  52019. for (var index = 0; index < this._animatables.length; index++) {
  52020. var animatable = this._animatables[index];
  52021. animatable.goToFrame(frame);
  52022. }
  52023. return this;
  52024. };
  52025. /**
  52026. * Dispose all associated resources
  52027. */
  52028. AnimationGroup.prototype.dispose = function () {
  52029. this._targetedAnimations = [];
  52030. this._animatables = [];
  52031. var index = this._scene.animationGroups.indexOf(this);
  52032. if (index > -1) {
  52033. this._scene.animationGroups.splice(index, 1);
  52034. }
  52035. };
  52036. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52037. // animatable should be taken out of the array
  52038. var idx = this._animatables.indexOf(animatable);
  52039. if (idx > -1) {
  52040. this._animatables.splice(idx, 1);
  52041. }
  52042. // all animatables were removed? animation group ended!
  52043. if (this._animatables.length === 0) {
  52044. this._isStarted = false;
  52045. this.onAnimationGroupEndObservable.notifyObservers(this);
  52046. }
  52047. };
  52048. return AnimationGroup;
  52049. }());
  52050. BABYLON.AnimationGroup = AnimationGroup;
  52051. })(BABYLON || (BABYLON = {}));
  52052. //# sourceMappingURL=babylon.animationGroup.js.map
  52053. var BABYLON;
  52054. (function (BABYLON) {
  52055. /**
  52056. * Defines a runtime animation
  52057. */
  52058. var RuntimeAnimation = /** @class */ (function () {
  52059. /**
  52060. * Create a new RuntimeAnimation object
  52061. * @param target defines the target of the animation
  52062. * @param animation defines the source animation object
  52063. * @param scene defines the hosting scene
  52064. * @param host defines the initiating Animatable
  52065. */
  52066. function RuntimeAnimation(target, animation, scene, host) {
  52067. var _this = this;
  52068. this._events = new Array();
  52069. /**
  52070. * The current frame of the runtime animation
  52071. */
  52072. this._currentFrame = 0;
  52073. /**
  52074. * The original value of the runtime animation
  52075. */
  52076. this._originalValue = new Array();
  52077. /**
  52078. * The offsets cache of the runtime animation
  52079. */
  52080. this._offsetsCache = {};
  52081. /**
  52082. * The high limits cache of the runtime animation
  52083. */
  52084. this._highLimitsCache = {};
  52085. /**
  52086. * Specifies if the runtime animation has been stopped
  52087. */
  52088. this._stopped = false;
  52089. /**
  52090. * The blending factor of the runtime animation
  52091. */
  52092. this._blendingFactor = 0;
  52093. /**
  52094. * The target path of the runtime animation
  52095. */
  52096. this._targetPath = "";
  52097. /**
  52098. * The weight of the runtime animation
  52099. */
  52100. this._weight = 1.0;
  52101. /**
  52102. * The ratio offset of the runtime animation
  52103. */
  52104. this._ratioOffset = 0;
  52105. /**
  52106. * The previous delay of the runtime animation
  52107. */
  52108. this._previousDelay = 0;
  52109. /**
  52110. * The previous ratio of the runtime animation
  52111. */
  52112. this._previousRatio = 0;
  52113. this._animation = animation;
  52114. this._target = target;
  52115. this._scene = scene;
  52116. this._host = host;
  52117. animation._runtimeAnimations.push(this);
  52118. // Cloning events locally
  52119. var events = animation.getEvents();
  52120. if (events && events.length > 0) {
  52121. events.forEach(function (e) {
  52122. _this._events.push(e._clone());
  52123. });
  52124. }
  52125. }
  52126. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52127. /**
  52128. * Gets the current frame of the runtime animation
  52129. */
  52130. get: function () {
  52131. return this._currentFrame;
  52132. },
  52133. enumerable: true,
  52134. configurable: true
  52135. });
  52136. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52137. /**
  52138. * Gets the weight of the runtime animation
  52139. */
  52140. get: function () {
  52141. return this._weight;
  52142. },
  52143. enumerable: true,
  52144. configurable: true
  52145. });
  52146. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52147. /**
  52148. * Gets the current value of the runtime animation
  52149. */
  52150. get: function () {
  52151. return this._currentValue;
  52152. },
  52153. enumerable: true,
  52154. configurable: true
  52155. });
  52156. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52157. /**
  52158. * Gets the target path of the runtime animation
  52159. */
  52160. get: function () {
  52161. return this._targetPath;
  52162. },
  52163. enumerable: true,
  52164. configurable: true
  52165. });
  52166. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52167. /**
  52168. * Gets the actual target of the runtime animation
  52169. */
  52170. get: function () {
  52171. return this._activeTarget;
  52172. },
  52173. enumerable: true,
  52174. configurable: true
  52175. });
  52176. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52177. /**
  52178. * Gets the animation from the runtime animation
  52179. */
  52180. get: function () {
  52181. return this._animation;
  52182. },
  52183. enumerable: true,
  52184. configurable: true
  52185. });
  52186. /**
  52187. * Resets the runtime animation to the beginning
  52188. * @param restoreOriginal defines whether to restore the target property to the original value
  52189. */
  52190. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52191. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52192. if (restoreOriginal) {
  52193. if (this._target instanceof Array) {
  52194. var index = 0;
  52195. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52196. var target = _a[_i];
  52197. if (this._originalValue[index] !== undefined) {
  52198. this._setValue(target, this._originalValue[index], -1);
  52199. }
  52200. index++;
  52201. }
  52202. }
  52203. else {
  52204. if (this._originalValue[0] !== undefined) {
  52205. this._setValue(this._target, this._originalValue[0], -1);
  52206. }
  52207. }
  52208. }
  52209. this._offsetsCache = {};
  52210. this._highLimitsCache = {};
  52211. this._currentFrame = 0;
  52212. this._blendingFactor = 0;
  52213. this._originalValue = new Array();
  52214. // Events
  52215. for (var index = 0; index < this._events.length; index++) {
  52216. this._events[index].isDone = false;
  52217. }
  52218. };
  52219. /**
  52220. * Specifies if the runtime animation is stopped
  52221. * @returns Boolean specifying if the runtime animation is stopped
  52222. */
  52223. RuntimeAnimation.prototype.isStopped = function () {
  52224. return this._stopped;
  52225. };
  52226. /**
  52227. * Disposes of the runtime animation
  52228. */
  52229. RuntimeAnimation.prototype.dispose = function () {
  52230. var index = this._animation.runtimeAnimations.indexOf(this);
  52231. if (index > -1) {
  52232. this._animation.runtimeAnimations.splice(index, 1);
  52233. }
  52234. };
  52235. /**
  52236. * Interpolates the animation from the current frame
  52237. * @param currentFrame The frame to interpolate the animation to
  52238. * @param repeatCount The number of times that the animation should loop
  52239. * @param loopMode The type of looping mode to use
  52240. * @param offsetValue Animation offset value
  52241. * @param highLimitValue The high limit value
  52242. * @returns The interpolated value
  52243. */
  52244. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52245. this._currentFrame = currentFrame;
  52246. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52247. this._workValue = BABYLON.Matrix.Zero();
  52248. }
  52249. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52250. };
  52251. /**
  52252. * Apply the interpolated value to the target
  52253. * @param currentValue defines the value computed by the animation
  52254. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52255. */
  52256. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52257. if (weight === void 0) { weight = 1.0; }
  52258. if (this._target instanceof Array) {
  52259. var index = 0;
  52260. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52261. var target = _a[_i];
  52262. this._setValue(target, currentValue, weight, index);
  52263. index++;
  52264. }
  52265. }
  52266. else {
  52267. this._setValue(this._target, currentValue, weight);
  52268. }
  52269. };
  52270. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52271. if (targetIndex === void 0) { targetIndex = 0; }
  52272. // Set value
  52273. var path;
  52274. var destination;
  52275. var targetPropertyPath = this._animation.targetPropertyPath;
  52276. if (targetPropertyPath.length > 1) {
  52277. var property = target[targetPropertyPath[0]];
  52278. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52279. property = property[targetPropertyPath[index]];
  52280. }
  52281. path = targetPropertyPath[targetPropertyPath.length - 1];
  52282. destination = property;
  52283. }
  52284. else {
  52285. path = targetPropertyPath[0];
  52286. destination = target;
  52287. }
  52288. this._targetPath = path;
  52289. this._activeTarget = destination;
  52290. this._weight = weight;
  52291. if (this._originalValue[targetIndex] === undefined) {
  52292. var originalValue = void 0;
  52293. if (destination.getRestPose && path === "_matrix") { // For bones
  52294. originalValue = destination.getRestPose();
  52295. }
  52296. else {
  52297. originalValue = destination[path];
  52298. }
  52299. if (originalValue && originalValue.clone) {
  52300. this._originalValue[targetIndex] = originalValue.clone();
  52301. }
  52302. else {
  52303. this._originalValue[targetIndex] = originalValue;
  52304. }
  52305. }
  52306. // Blending
  52307. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52308. if (enableBlending && this._blendingFactor <= 1.0) {
  52309. if (!this._originalBlendValue) {
  52310. var originalValue = destination[path];
  52311. if (originalValue.clone) {
  52312. this._originalBlendValue = originalValue.clone();
  52313. }
  52314. else {
  52315. this._originalBlendValue = originalValue;
  52316. }
  52317. }
  52318. if (this._originalBlendValue.m) { // Matrix
  52319. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52320. if (this._currentValue) {
  52321. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52322. }
  52323. else {
  52324. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52325. }
  52326. }
  52327. else {
  52328. if (this._currentValue) {
  52329. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52330. }
  52331. else {
  52332. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52333. }
  52334. }
  52335. }
  52336. else {
  52337. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52338. }
  52339. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52340. this._blendingFactor += blendingSpeed;
  52341. }
  52342. else {
  52343. this._currentValue = currentValue;
  52344. }
  52345. if (weight !== -1.0) {
  52346. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52347. }
  52348. else {
  52349. destination[path] = this._currentValue;
  52350. }
  52351. if (target.markAsDirty) {
  52352. target.markAsDirty(this._animation.targetProperty);
  52353. }
  52354. };
  52355. /**
  52356. * Gets the loop pmode of the runtime animation
  52357. * @returns Loop Mode
  52358. */
  52359. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52360. if (this._target && this._target.animationPropertiesOverride) {
  52361. return this._target.animationPropertiesOverride.loopMode;
  52362. }
  52363. return this._animation.loopMode;
  52364. };
  52365. /**
  52366. * Move the current animation to a given frame
  52367. * @param frame defines the frame to move to
  52368. */
  52369. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52370. var keys = this._animation.getKeys();
  52371. if (frame < keys[0].frame) {
  52372. frame = keys[0].frame;
  52373. }
  52374. else if (frame > keys[keys.length - 1].frame) {
  52375. frame = keys[keys.length - 1].frame;
  52376. }
  52377. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52378. this.setValue(currentValue, -1);
  52379. };
  52380. /**
  52381. * @hidden Internal use only
  52382. */
  52383. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52384. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52385. this._ratioOffset = this._previousRatio - newRatio;
  52386. };
  52387. /**
  52388. * Execute the current animation
  52389. * @param delay defines the delay to add to the current frame
  52390. * @param from defines the lower bound of the animation range
  52391. * @param to defines the upper bound of the animation range
  52392. * @param loop defines if the current animation must loop
  52393. * @param speedRatio defines the current speed ratio
  52394. * @param weight defines the weight of the animation (default is -1 so no weight)
  52395. * @returns a boolean indicating if the animation has ended
  52396. */
  52397. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52398. if (weight === void 0) { weight = -1.0; }
  52399. var targetPropertyPath = this._animation.targetPropertyPath;
  52400. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52401. this._stopped = true;
  52402. return false;
  52403. }
  52404. var returnValue = true;
  52405. var keys = this._animation.getKeys();
  52406. // Adding a start key at frame 0 if missing
  52407. if (keys[0].frame !== 0) {
  52408. var newKey = { frame: 0, value: keys[0].value };
  52409. keys.splice(0, 0, newKey);
  52410. }
  52411. // Check limits
  52412. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52413. from = keys[0].frame;
  52414. }
  52415. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52416. to = keys[keys.length - 1].frame;
  52417. }
  52418. //to and from cannot be the same key
  52419. if (from === to) {
  52420. if (from > keys[0].frame) {
  52421. from--;
  52422. }
  52423. else if (to < keys[keys.length - 1].frame) {
  52424. to++;
  52425. }
  52426. }
  52427. // Compute ratio
  52428. var range = to - from;
  52429. var offsetValue;
  52430. // ratio represents the frame delta between from and to
  52431. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52432. var highLimitValue = 0;
  52433. this._previousDelay = delay;
  52434. this._previousRatio = ratio;
  52435. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52436. returnValue = false;
  52437. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52438. }
  52439. else {
  52440. // Get max value if required
  52441. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52442. var keyOffset = to.toString() + from.toString();
  52443. if (!this._offsetsCache[keyOffset]) {
  52444. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52445. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52446. switch (this._animation.dataType) {
  52447. // Float
  52448. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52449. this._offsetsCache[keyOffset] = toValue - fromValue;
  52450. break;
  52451. // Quaternion
  52452. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52453. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52454. break;
  52455. // Vector3
  52456. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52457. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52458. // Vector2
  52459. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52460. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52461. // Size
  52462. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52463. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52464. // Color3
  52465. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52466. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52467. default:
  52468. break;
  52469. }
  52470. this._highLimitsCache[keyOffset] = toValue;
  52471. }
  52472. highLimitValue = this._highLimitsCache[keyOffset];
  52473. offsetValue = this._offsetsCache[keyOffset];
  52474. }
  52475. }
  52476. if (offsetValue === undefined) {
  52477. switch (this._animation.dataType) {
  52478. // Float
  52479. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52480. offsetValue = 0;
  52481. break;
  52482. // Quaternion
  52483. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52484. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52485. break;
  52486. // Vector3
  52487. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52488. offsetValue = BABYLON.Vector3.Zero();
  52489. break;
  52490. // Vector2
  52491. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52492. offsetValue = BABYLON.Vector2.Zero();
  52493. break;
  52494. // Size
  52495. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52496. offsetValue = BABYLON.Size.Zero();
  52497. break;
  52498. // Color3
  52499. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52500. offsetValue = BABYLON.Color3.Black();
  52501. }
  52502. }
  52503. // Compute value
  52504. var repeatCount = (ratio / range) >> 0;
  52505. var currentFrame = returnValue ? from + ratio % range : to;
  52506. // Need to normalize?
  52507. if (this._host && this._host.syncRoot) {
  52508. var syncRoot = this._host.syncRoot;
  52509. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52510. currentFrame = from + (to - from) * hostNormalizedFrame;
  52511. }
  52512. // Reset events if looping
  52513. var events = this._events;
  52514. if (range > 0 && this.currentFrame > currentFrame ||
  52515. range < 0 && this.currentFrame < currentFrame) {
  52516. // Need to reset animation events
  52517. for (var index = 0; index < events.length; index++) {
  52518. if (!events[index].onlyOnce) {
  52519. // reset event, the animation is looping
  52520. events[index].isDone = false;
  52521. }
  52522. }
  52523. }
  52524. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52525. // Set value
  52526. this.setValue(currentValue, weight);
  52527. // Check events
  52528. for (var index = 0; index < events.length; index++) {
  52529. // Make sure current frame has passed event frame and that event frame is within the current range
  52530. // Also, handle both forward and reverse animations
  52531. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52532. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52533. var event = events[index];
  52534. if (!event.isDone) {
  52535. // If event should be done only once, remove it.
  52536. if (event.onlyOnce) {
  52537. events.splice(index, 1);
  52538. index--;
  52539. }
  52540. event.isDone = true;
  52541. event.action();
  52542. } // Don't do anything if the event has already be done.
  52543. }
  52544. }
  52545. if (!returnValue) {
  52546. this._stopped = true;
  52547. }
  52548. return returnValue;
  52549. };
  52550. return RuntimeAnimation;
  52551. }());
  52552. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52553. })(BABYLON || (BABYLON = {}));
  52554. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52555. var BABYLON;
  52556. (function (BABYLON) {
  52557. var Animatable = /** @class */ (function () {
  52558. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52559. if (fromFrame === void 0) { fromFrame = 0; }
  52560. if (toFrame === void 0) { toFrame = 100; }
  52561. if (loopAnimation === void 0) { loopAnimation = false; }
  52562. if (speedRatio === void 0) { speedRatio = 1.0; }
  52563. this.target = target;
  52564. this.fromFrame = fromFrame;
  52565. this.toFrame = toFrame;
  52566. this.loopAnimation = loopAnimation;
  52567. this.onAnimationEnd = onAnimationEnd;
  52568. this._localDelayOffset = null;
  52569. this._pausedDelay = null;
  52570. this._runtimeAnimations = new Array();
  52571. this._paused = false;
  52572. this._speedRatio = 1;
  52573. this._weight = -1.0;
  52574. this.animationStarted = false;
  52575. /**
  52576. * Observer raised when the animation ends
  52577. */
  52578. this.onAnimationEndObservable = new BABYLON.Observable();
  52579. this._scene = scene;
  52580. if (animations) {
  52581. this.appendAnimations(target, animations);
  52582. }
  52583. this._speedRatio = speedRatio;
  52584. scene._activeAnimatables.push(this);
  52585. }
  52586. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52587. /**
  52588. * Gets the root Animatable used to synchronize and normalize animations
  52589. */
  52590. get: function () {
  52591. return this._syncRoot;
  52592. },
  52593. enumerable: true,
  52594. configurable: true
  52595. });
  52596. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52597. /**
  52598. * Gets the current frame of the first RuntimeAnimation
  52599. * Used to synchronize Animatables
  52600. */
  52601. get: function () {
  52602. if (this._runtimeAnimations.length === 0) {
  52603. return 0;
  52604. }
  52605. return this._runtimeAnimations[0].currentFrame;
  52606. },
  52607. enumerable: true,
  52608. configurable: true
  52609. });
  52610. Object.defineProperty(Animatable.prototype, "weight", {
  52611. /**
  52612. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52613. */
  52614. get: function () {
  52615. return this._weight;
  52616. },
  52617. set: function (value) {
  52618. if (value === -1) { // -1 is ok and means no weight
  52619. this._weight = -1;
  52620. return;
  52621. }
  52622. // Else weight must be in [0, 1] range
  52623. this._weight = Math.min(Math.max(value, 0), 1.0);
  52624. },
  52625. enumerable: true,
  52626. configurable: true
  52627. });
  52628. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52629. /**
  52630. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52631. */
  52632. get: function () {
  52633. return this._speedRatio;
  52634. },
  52635. set: function (value) {
  52636. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52637. var animation = this._runtimeAnimations[index];
  52638. animation._prepareForSpeedRatioChange(value);
  52639. }
  52640. this._speedRatio = value;
  52641. },
  52642. enumerable: true,
  52643. configurable: true
  52644. });
  52645. // Methods
  52646. /**
  52647. * Synchronize and normalize current Animatable with a source Animatable
  52648. * This is useful when using animation weights and when animations are not of the same length
  52649. * @param root defines the root Animatable to synchronize with
  52650. * @returns the current Animatable
  52651. */
  52652. Animatable.prototype.syncWith = function (root) {
  52653. this._syncRoot = root;
  52654. if (root) {
  52655. // Make sure this animatable will animate after the root
  52656. var index = this._scene._activeAnimatables.indexOf(this);
  52657. if (index > -1) {
  52658. this._scene._activeAnimatables.splice(index, 1);
  52659. this._scene._activeAnimatables.push(this);
  52660. }
  52661. }
  52662. return this;
  52663. };
  52664. Animatable.prototype.getAnimations = function () {
  52665. return this._runtimeAnimations;
  52666. };
  52667. Animatable.prototype.appendAnimations = function (target, animations) {
  52668. for (var index = 0; index < animations.length; index++) {
  52669. var animation = animations[index];
  52670. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52671. }
  52672. };
  52673. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52674. var runtimeAnimations = this._runtimeAnimations;
  52675. for (var index = 0; index < runtimeAnimations.length; index++) {
  52676. if (runtimeAnimations[index].animation.targetProperty === property) {
  52677. return runtimeAnimations[index].animation;
  52678. }
  52679. }
  52680. return null;
  52681. };
  52682. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52683. var runtimeAnimations = this._runtimeAnimations;
  52684. for (var index = 0; index < runtimeAnimations.length; index++) {
  52685. if (runtimeAnimations[index].animation.targetProperty === property) {
  52686. return runtimeAnimations[index];
  52687. }
  52688. }
  52689. return null;
  52690. };
  52691. Animatable.prototype.reset = function () {
  52692. var runtimeAnimations = this._runtimeAnimations;
  52693. for (var index = 0; index < runtimeAnimations.length; index++) {
  52694. runtimeAnimations[index].reset(true);
  52695. }
  52696. this._localDelayOffset = null;
  52697. this._pausedDelay = null;
  52698. };
  52699. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52700. var runtimeAnimations = this._runtimeAnimations;
  52701. for (var index = 0; index < runtimeAnimations.length; index++) {
  52702. runtimeAnimations[index].animation.enableBlending = true;
  52703. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52704. }
  52705. };
  52706. Animatable.prototype.disableBlending = function () {
  52707. var runtimeAnimations = this._runtimeAnimations;
  52708. for (var index = 0; index < runtimeAnimations.length; index++) {
  52709. runtimeAnimations[index].animation.enableBlending = false;
  52710. }
  52711. };
  52712. Animatable.prototype.goToFrame = function (frame) {
  52713. var runtimeAnimations = this._runtimeAnimations;
  52714. if (runtimeAnimations[0]) {
  52715. var fps = runtimeAnimations[0].animation.framePerSecond;
  52716. var currentFrame = runtimeAnimations[0].currentFrame;
  52717. var adjustTime = frame - currentFrame;
  52718. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52719. if (this._localDelayOffset === null) {
  52720. this._localDelayOffset = 0;
  52721. }
  52722. this._localDelayOffset -= delay;
  52723. }
  52724. for (var index = 0; index < runtimeAnimations.length; index++) {
  52725. runtimeAnimations[index].goToFrame(frame);
  52726. }
  52727. };
  52728. Animatable.prototype.pause = function () {
  52729. if (this._paused) {
  52730. return;
  52731. }
  52732. this._paused = true;
  52733. };
  52734. Animatable.prototype.restart = function () {
  52735. this._paused = false;
  52736. };
  52737. Animatable.prototype._raiseOnAnimationEnd = function () {
  52738. if (this.onAnimationEnd) {
  52739. this.onAnimationEnd();
  52740. }
  52741. this.onAnimationEndObservable.notifyObservers(this);
  52742. };
  52743. Animatable.prototype.stop = function (animationName) {
  52744. if (animationName) {
  52745. var idx = this._scene._activeAnimatables.indexOf(this);
  52746. if (idx > -1) {
  52747. var runtimeAnimations = this._runtimeAnimations;
  52748. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52749. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52750. continue;
  52751. }
  52752. runtimeAnimations[index].dispose();
  52753. runtimeAnimations.splice(index, 1);
  52754. }
  52755. if (runtimeAnimations.length == 0) {
  52756. this._scene._activeAnimatables.splice(idx, 1);
  52757. this._raiseOnAnimationEnd();
  52758. }
  52759. }
  52760. }
  52761. else {
  52762. var index = this._scene._activeAnimatables.indexOf(this);
  52763. if (index > -1) {
  52764. this._scene._activeAnimatables.splice(index, 1);
  52765. var runtimeAnimations = this._runtimeAnimations;
  52766. for (var index = 0; index < runtimeAnimations.length; index++) {
  52767. runtimeAnimations[index].dispose();
  52768. }
  52769. this._raiseOnAnimationEnd();
  52770. }
  52771. }
  52772. };
  52773. /**
  52774. * Wait asynchronously for the animation to end
  52775. * @returns a promise which will be fullfilled when the animation ends
  52776. */
  52777. Animatable.prototype.waitAsync = function () {
  52778. var _this = this;
  52779. return new Promise(function (resolve, reject) {
  52780. _this.onAnimationEndObservable.add(function () {
  52781. resolve(_this);
  52782. }, undefined, undefined, _this, true);
  52783. });
  52784. };
  52785. /** @hidden */
  52786. Animatable.prototype._animate = function (delay) {
  52787. if (this._paused) {
  52788. this.animationStarted = false;
  52789. if (this._pausedDelay === null) {
  52790. this._pausedDelay = delay;
  52791. }
  52792. return true;
  52793. }
  52794. if (this._localDelayOffset === null) {
  52795. this._localDelayOffset = delay;
  52796. this._pausedDelay = null;
  52797. }
  52798. else if (this._pausedDelay !== null) {
  52799. this._localDelayOffset += delay - this._pausedDelay;
  52800. this._pausedDelay = null;
  52801. }
  52802. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52803. return true;
  52804. }
  52805. // Animating
  52806. var running = false;
  52807. var runtimeAnimations = this._runtimeAnimations;
  52808. var index;
  52809. for (index = 0; index < runtimeAnimations.length; index++) {
  52810. var animation = runtimeAnimations[index];
  52811. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52812. running = running || isRunning;
  52813. }
  52814. this.animationStarted = running;
  52815. if (!running) {
  52816. // Remove from active animatables
  52817. index = this._scene._activeAnimatables.indexOf(this);
  52818. this._scene._activeAnimatables.splice(index, 1);
  52819. // Dispose all runtime animations
  52820. for (index = 0; index < runtimeAnimations.length; index++) {
  52821. runtimeAnimations[index].dispose();
  52822. }
  52823. this._raiseOnAnimationEnd();
  52824. this.onAnimationEnd = null;
  52825. this.onAnimationEndObservable.clear();
  52826. }
  52827. return running;
  52828. };
  52829. return Animatable;
  52830. }());
  52831. BABYLON.Animatable = Animatable;
  52832. })(BABYLON || (BABYLON = {}));
  52833. //# sourceMappingURL=babylon.animatable.js.map
  52834. var BABYLON;
  52835. (function (BABYLON) {
  52836. var EasingFunction = /** @class */ (function () {
  52837. function EasingFunction() {
  52838. // Properties
  52839. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52840. }
  52841. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52842. get: function () {
  52843. return EasingFunction._EASINGMODE_EASEIN;
  52844. },
  52845. enumerable: true,
  52846. configurable: true
  52847. });
  52848. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52849. get: function () {
  52850. return EasingFunction._EASINGMODE_EASEOUT;
  52851. },
  52852. enumerable: true,
  52853. configurable: true
  52854. });
  52855. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52856. get: function () {
  52857. return EasingFunction._EASINGMODE_EASEINOUT;
  52858. },
  52859. enumerable: true,
  52860. configurable: true
  52861. });
  52862. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52863. var n = Math.min(Math.max(easingMode, 0), 2);
  52864. this._easingMode = n;
  52865. };
  52866. EasingFunction.prototype.getEasingMode = function () {
  52867. return this._easingMode;
  52868. };
  52869. EasingFunction.prototype.easeInCore = function (gradient) {
  52870. throw new Error('You must implement this method');
  52871. };
  52872. EasingFunction.prototype.ease = function (gradient) {
  52873. switch (this._easingMode) {
  52874. case EasingFunction.EASINGMODE_EASEIN:
  52875. return this.easeInCore(gradient);
  52876. case EasingFunction.EASINGMODE_EASEOUT:
  52877. return (1 - this.easeInCore(1 - gradient));
  52878. }
  52879. if (gradient >= 0.5) {
  52880. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52881. }
  52882. return (this.easeInCore(gradient * 2) * 0.5);
  52883. };
  52884. //Statics
  52885. EasingFunction._EASINGMODE_EASEIN = 0;
  52886. EasingFunction._EASINGMODE_EASEOUT = 1;
  52887. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52888. return EasingFunction;
  52889. }());
  52890. BABYLON.EasingFunction = EasingFunction;
  52891. var CircleEase = /** @class */ (function (_super) {
  52892. __extends(CircleEase, _super);
  52893. function CircleEase() {
  52894. return _super !== null && _super.apply(this, arguments) || this;
  52895. }
  52896. CircleEase.prototype.easeInCore = function (gradient) {
  52897. gradient = Math.max(0, Math.min(1, gradient));
  52898. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52899. };
  52900. return CircleEase;
  52901. }(EasingFunction));
  52902. BABYLON.CircleEase = CircleEase;
  52903. var BackEase = /** @class */ (function (_super) {
  52904. __extends(BackEase, _super);
  52905. function BackEase(amplitude) {
  52906. if (amplitude === void 0) { amplitude = 1; }
  52907. var _this = _super.call(this) || this;
  52908. _this.amplitude = amplitude;
  52909. return _this;
  52910. }
  52911. BackEase.prototype.easeInCore = function (gradient) {
  52912. var num = Math.max(0, this.amplitude);
  52913. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52914. };
  52915. return BackEase;
  52916. }(EasingFunction));
  52917. BABYLON.BackEase = BackEase;
  52918. var BounceEase = /** @class */ (function (_super) {
  52919. __extends(BounceEase, _super);
  52920. function BounceEase(bounces, bounciness) {
  52921. if (bounces === void 0) { bounces = 3; }
  52922. if (bounciness === void 0) { bounciness = 2; }
  52923. var _this = _super.call(this) || this;
  52924. _this.bounces = bounces;
  52925. _this.bounciness = bounciness;
  52926. return _this;
  52927. }
  52928. BounceEase.prototype.easeInCore = function (gradient) {
  52929. var y = Math.max(0.0, this.bounces);
  52930. var bounciness = this.bounciness;
  52931. if (bounciness <= 1.0) {
  52932. bounciness = 1.001;
  52933. }
  52934. var num9 = Math.pow(bounciness, y);
  52935. var num5 = 1.0 - bounciness;
  52936. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52937. var num15 = gradient * num4;
  52938. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52939. var num3 = Math.floor(num65);
  52940. var num13 = num3 + 1.0;
  52941. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52942. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52943. var num7 = (num8 + num12) * 0.5;
  52944. var num6 = gradient - num7;
  52945. var num2 = num7 - num8;
  52946. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52947. };
  52948. return BounceEase;
  52949. }(EasingFunction));
  52950. BABYLON.BounceEase = BounceEase;
  52951. var CubicEase = /** @class */ (function (_super) {
  52952. __extends(CubicEase, _super);
  52953. function CubicEase() {
  52954. return _super !== null && _super.apply(this, arguments) || this;
  52955. }
  52956. CubicEase.prototype.easeInCore = function (gradient) {
  52957. return (gradient * gradient * gradient);
  52958. };
  52959. return CubicEase;
  52960. }(EasingFunction));
  52961. BABYLON.CubicEase = CubicEase;
  52962. var ElasticEase = /** @class */ (function (_super) {
  52963. __extends(ElasticEase, _super);
  52964. function ElasticEase(oscillations, springiness) {
  52965. if (oscillations === void 0) { oscillations = 3; }
  52966. if (springiness === void 0) { springiness = 3; }
  52967. var _this = _super.call(this) || this;
  52968. _this.oscillations = oscillations;
  52969. _this.springiness = springiness;
  52970. return _this;
  52971. }
  52972. ElasticEase.prototype.easeInCore = function (gradient) {
  52973. var num2;
  52974. var num3 = Math.max(0.0, this.oscillations);
  52975. var num = Math.max(0.0, this.springiness);
  52976. if (num == 0) {
  52977. num2 = gradient;
  52978. }
  52979. else {
  52980. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52981. }
  52982. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52983. };
  52984. return ElasticEase;
  52985. }(EasingFunction));
  52986. BABYLON.ElasticEase = ElasticEase;
  52987. var ExponentialEase = /** @class */ (function (_super) {
  52988. __extends(ExponentialEase, _super);
  52989. function ExponentialEase(exponent) {
  52990. if (exponent === void 0) { exponent = 2; }
  52991. var _this = _super.call(this) || this;
  52992. _this.exponent = exponent;
  52993. return _this;
  52994. }
  52995. ExponentialEase.prototype.easeInCore = function (gradient) {
  52996. if (this.exponent <= 0) {
  52997. return gradient;
  52998. }
  52999. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53000. };
  53001. return ExponentialEase;
  53002. }(EasingFunction));
  53003. BABYLON.ExponentialEase = ExponentialEase;
  53004. var PowerEase = /** @class */ (function (_super) {
  53005. __extends(PowerEase, _super);
  53006. function PowerEase(power) {
  53007. if (power === void 0) { power = 2; }
  53008. var _this = _super.call(this) || this;
  53009. _this.power = power;
  53010. return _this;
  53011. }
  53012. PowerEase.prototype.easeInCore = function (gradient) {
  53013. var y = Math.max(0.0, this.power);
  53014. return Math.pow(gradient, y);
  53015. };
  53016. return PowerEase;
  53017. }(EasingFunction));
  53018. BABYLON.PowerEase = PowerEase;
  53019. var QuadraticEase = /** @class */ (function (_super) {
  53020. __extends(QuadraticEase, _super);
  53021. function QuadraticEase() {
  53022. return _super !== null && _super.apply(this, arguments) || this;
  53023. }
  53024. QuadraticEase.prototype.easeInCore = function (gradient) {
  53025. return (gradient * gradient);
  53026. };
  53027. return QuadraticEase;
  53028. }(EasingFunction));
  53029. BABYLON.QuadraticEase = QuadraticEase;
  53030. var QuarticEase = /** @class */ (function (_super) {
  53031. __extends(QuarticEase, _super);
  53032. function QuarticEase() {
  53033. return _super !== null && _super.apply(this, arguments) || this;
  53034. }
  53035. QuarticEase.prototype.easeInCore = function (gradient) {
  53036. return (gradient * gradient * gradient * gradient);
  53037. };
  53038. return QuarticEase;
  53039. }(EasingFunction));
  53040. BABYLON.QuarticEase = QuarticEase;
  53041. var QuinticEase = /** @class */ (function (_super) {
  53042. __extends(QuinticEase, _super);
  53043. function QuinticEase() {
  53044. return _super !== null && _super.apply(this, arguments) || this;
  53045. }
  53046. QuinticEase.prototype.easeInCore = function (gradient) {
  53047. return (gradient * gradient * gradient * gradient * gradient);
  53048. };
  53049. return QuinticEase;
  53050. }(EasingFunction));
  53051. BABYLON.QuinticEase = QuinticEase;
  53052. var SineEase = /** @class */ (function (_super) {
  53053. __extends(SineEase, _super);
  53054. function SineEase() {
  53055. return _super !== null && _super.apply(this, arguments) || this;
  53056. }
  53057. SineEase.prototype.easeInCore = function (gradient) {
  53058. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53059. };
  53060. return SineEase;
  53061. }(EasingFunction));
  53062. BABYLON.SineEase = SineEase;
  53063. var BezierCurveEase = /** @class */ (function (_super) {
  53064. __extends(BezierCurveEase, _super);
  53065. function BezierCurveEase(x1, y1, x2, y2) {
  53066. if (x1 === void 0) { x1 = 0; }
  53067. if (y1 === void 0) { y1 = 0; }
  53068. if (x2 === void 0) { x2 = 1; }
  53069. if (y2 === void 0) { y2 = 1; }
  53070. var _this = _super.call(this) || this;
  53071. _this.x1 = x1;
  53072. _this.y1 = y1;
  53073. _this.x2 = x2;
  53074. _this.y2 = y2;
  53075. return _this;
  53076. }
  53077. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53078. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53079. };
  53080. return BezierCurveEase;
  53081. }(EasingFunction));
  53082. BABYLON.BezierCurveEase = BezierCurveEase;
  53083. })(BABYLON || (BABYLON = {}));
  53084. //# sourceMappingURL=babylon.easing.js.map
  53085. var BABYLON;
  53086. (function (BABYLON) {
  53087. /**
  53088. * A Condition applied to an Action
  53089. */
  53090. var Condition = /** @class */ (function () {
  53091. /**
  53092. * Creates a new Condition
  53093. * @param actionManager the manager of the action the condition is applied to
  53094. */
  53095. function Condition(actionManager) {
  53096. this._actionManager = actionManager;
  53097. }
  53098. /**
  53099. * Check if the current condition is valid
  53100. * @returns a boolean
  53101. */
  53102. Condition.prototype.isValid = function () {
  53103. return true;
  53104. };
  53105. /**
  53106. * Internal only
  53107. * @hidden
  53108. */
  53109. Condition.prototype._getProperty = function (propertyPath) {
  53110. return this._actionManager._getProperty(propertyPath);
  53111. };
  53112. /**
  53113. * Internal only
  53114. * @hidden
  53115. */
  53116. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53117. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53118. };
  53119. /**
  53120. * Serialize placeholder for child classes
  53121. * @returns the serialized object
  53122. */
  53123. Condition.prototype.serialize = function () {
  53124. };
  53125. /**
  53126. * Internal only
  53127. * @hidden
  53128. */
  53129. Condition.prototype._serialize = function (serializedCondition) {
  53130. return {
  53131. type: 2,
  53132. children: [],
  53133. name: serializedCondition.name,
  53134. properties: serializedCondition.properties
  53135. };
  53136. };
  53137. return Condition;
  53138. }());
  53139. BABYLON.Condition = Condition;
  53140. /**
  53141. * Defines specific conditional operators as extensions of Condition
  53142. */
  53143. var ValueCondition = /** @class */ (function (_super) {
  53144. __extends(ValueCondition, _super);
  53145. /**
  53146. * Creates a new ValueCondition
  53147. * @param actionManager manager for the action the condition applies to
  53148. * @param target for the action
  53149. * @param propertyPath path to specify the property of the target the conditional operator uses
  53150. * @param value the value compared by the conditional operator against the current value of the property
  53151. * @param operator the conditional operator, default ValueCondition.IsEqual
  53152. */
  53153. function ValueCondition(actionManager, target,
  53154. /** path to specify the property of the target the conditional operator uses */
  53155. propertyPath,
  53156. /** the value compared by the conditional operator against the current value of the property */
  53157. value,
  53158. /** the conditional operator, default ValueCondition.IsEqual */
  53159. operator) {
  53160. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53161. var _this = _super.call(this, actionManager) || this;
  53162. _this.propertyPath = propertyPath;
  53163. _this.value = value;
  53164. _this.operator = operator;
  53165. _this._target = target;
  53166. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53167. _this._property = _this._getProperty(_this.propertyPath);
  53168. return _this;
  53169. }
  53170. Object.defineProperty(ValueCondition, "IsEqual", {
  53171. /**
  53172. * returns the number for IsEqual
  53173. */
  53174. get: function () {
  53175. return ValueCondition._IsEqual;
  53176. },
  53177. enumerable: true,
  53178. configurable: true
  53179. });
  53180. Object.defineProperty(ValueCondition, "IsDifferent", {
  53181. /**
  53182. * Returns the number for IsDifferent
  53183. */
  53184. get: function () {
  53185. return ValueCondition._IsDifferent;
  53186. },
  53187. enumerable: true,
  53188. configurable: true
  53189. });
  53190. Object.defineProperty(ValueCondition, "IsGreater", {
  53191. /**
  53192. * Returns the number for IsGreater
  53193. */
  53194. get: function () {
  53195. return ValueCondition._IsGreater;
  53196. },
  53197. enumerable: true,
  53198. configurable: true
  53199. });
  53200. Object.defineProperty(ValueCondition, "IsLesser", {
  53201. /**
  53202. * Returns the number for IsLesser
  53203. */
  53204. get: function () {
  53205. return ValueCondition._IsLesser;
  53206. },
  53207. enumerable: true,
  53208. configurable: true
  53209. });
  53210. /**
  53211. * Compares the given value with the property value for the specified conditional operator
  53212. * @returns the result of the comparison
  53213. */
  53214. ValueCondition.prototype.isValid = function () {
  53215. switch (this.operator) {
  53216. case ValueCondition.IsGreater:
  53217. return this._effectiveTarget[this._property] > this.value;
  53218. case ValueCondition.IsLesser:
  53219. return this._effectiveTarget[this._property] < this.value;
  53220. case ValueCondition.IsEqual:
  53221. case ValueCondition.IsDifferent:
  53222. var check;
  53223. if (this.value.equals) {
  53224. check = this.value.equals(this._effectiveTarget[this._property]);
  53225. }
  53226. else {
  53227. check = this.value === this._effectiveTarget[this._property];
  53228. }
  53229. return this.operator === ValueCondition.IsEqual ? check : !check;
  53230. }
  53231. return false;
  53232. };
  53233. /**
  53234. * Serialize the ValueCondition into a JSON compatible object
  53235. * @returns serialization object
  53236. */
  53237. ValueCondition.prototype.serialize = function () {
  53238. return this._serialize({
  53239. name: "ValueCondition",
  53240. properties: [
  53241. BABYLON.Action._GetTargetProperty(this._target),
  53242. { name: "propertyPath", value: this.propertyPath },
  53243. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53244. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53245. ]
  53246. });
  53247. };
  53248. /**
  53249. * Gets the name of the conditional operator for the ValueCondition
  53250. * @param operator the conditional operator
  53251. * @returns the name
  53252. */
  53253. ValueCondition.GetOperatorName = function (operator) {
  53254. switch (operator) {
  53255. case ValueCondition._IsEqual: return "IsEqual";
  53256. case ValueCondition._IsDifferent: return "IsDifferent";
  53257. case ValueCondition._IsGreater: return "IsGreater";
  53258. case ValueCondition._IsLesser: return "IsLesser";
  53259. default: return "";
  53260. }
  53261. };
  53262. /**
  53263. * Internal only
  53264. * @hidden
  53265. */
  53266. ValueCondition._IsEqual = 0;
  53267. /**
  53268. * Internal only
  53269. * @hidden
  53270. */
  53271. ValueCondition._IsDifferent = 1;
  53272. /**
  53273. * Internal only
  53274. * @hidden
  53275. */
  53276. ValueCondition._IsGreater = 2;
  53277. /**
  53278. * Internal only
  53279. * @hidden
  53280. */
  53281. ValueCondition._IsLesser = 3;
  53282. return ValueCondition;
  53283. }(Condition));
  53284. BABYLON.ValueCondition = ValueCondition;
  53285. /**
  53286. * Defines a predicate condition as an extension of Condition
  53287. */
  53288. var PredicateCondition = /** @class */ (function (_super) {
  53289. __extends(PredicateCondition, _super);
  53290. /**
  53291. * Creates a new PredicateCondition
  53292. * @param actionManager manager for the action the condition applies to
  53293. * @param predicate defines the predicate function used to validate the condition
  53294. */
  53295. function PredicateCondition(actionManager,
  53296. /** defines the predicate function used to validate the condition */
  53297. predicate) {
  53298. var _this = _super.call(this, actionManager) || this;
  53299. _this.predicate = predicate;
  53300. return _this;
  53301. }
  53302. /**
  53303. * @returns the validity of the predicate condition
  53304. */
  53305. PredicateCondition.prototype.isValid = function () {
  53306. return this.predicate();
  53307. };
  53308. return PredicateCondition;
  53309. }(Condition));
  53310. BABYLON.PredicateCondition = PredicateCondition;
  53311. /**
  53312. * Defines a state condition as an extension of Condition
  53313. */
  53314. var StateCondition = /** @class */ (function (_super) {
  53315. __extends(StateCondition, _super);
  53316. /**
  53317. * Creates a new StateCondition
  53318. * @param actionManager manager for the action the condition applies to
  53319. * @param target of the condition
  53320. * @param value to compare with target state
  53321. */
  53322. function StateCondition(actionManager, target, value) {
  53323. var _this = _super.call(this, actionManager) || this;
  53324. _this.value = value;
  53325. _this._target = target;
  53326. return _this;
  53327. }
  53328. /**
  53329. * @returns the validity of the state
  53330. */
  53331. StateCondition.prototype.isValid = function () {
  53332. return this._target.state === this.value;
  53333. };
  53334. /**
  53335. * Serialize the StateCondition into a JSON compatible object
  53336. * @returns serialization object
  53337. */
  53338. StateCondition.prototype.serialize = function () {
  53339. return this._serialize({
  53340. name: "StateCondition",
  53341. properties: [
  53342. BABYLON.Action._GetTargetProperty(this._target),
  53343. { name: "value", value: this.value }
  53344. ]
  53345. });
  53346. };
  53347. return StateCondition;
  53348. }(Condition));
  53349. BABYLON.StateCondition = StateCondition;
  53350. })(BABYLON || (BABYLON = {}));
  53351. //# sourceMappingURL=babylon.condition.js.map
  53352. var BABYLON;
  53353. (function (BABYLON) {
  53354. /**
  53355. * The action to be carried out following a trigger
  53356. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53357. */
  53358. var Action = /** @class */ (function () {
  53359. /**
  53360. * Creates a new Action
  53361. * @param triggerOptions the trigger, with or without parameters, for the action
  53362. * @param condition an optional determinant of action
  53363. */
  53364. function Action(
  53365. /** the trigger, with or without parameters, for the action */
  53366. triggerOptions, condition) {
  53367. this.triggerOptions = triggerOptions;
  53368. /**
  53369. * An event triggered prior to action being executed.
  53370. */
  53371. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53372. if (triggerOptions.parameter) {
  53373. this.trigger = triggerOptions.trigger;
  53374. this._triggerParameter = triggerOptions.parameter;
  53375. }
  53376. else {
  53377. this.trigger = triggerOptions;
  53378. }
  53379. this._nextActiveAction = this;
  53380. this._condition = condition;
  53381. }
  53382. /**
  53383. * Internal only
  53384. * @hidden
  53385. */
  53386. Action.prototype._prepare = function () {
  53387. };
  53388. /**
  53389. * Gets the trigger parameters
  53390. * @returns the trigger parameters
  53391. */
  53392. Action.prototype.getTriggerParameter = function () {
  53393. return this._triggerParameter;
  53394. };
  53395. /**
  53396. * Internal only - executes current action event
  53397. * @hidden
  53398. */
  53399. Action.prototype._executeCurrent = function (evt) {
  53400. if (this._nextActiveAction._condition) {
  53401. var condition = this._nextActiveAction._condition;
  53402. var currentRenderId = this._actionManager.getScene().getRenderId();
  53403. // We cache the current evaluation for the current frame
  53404. if (condition._evaluationId === currentRenderId) {
  53405. if (!condition._currentResult) {
  53406. return;
  53407. }
  53408. }
  53409. else {
  53410. condition._evaluationId = currentRenderId;
  53411. if (!condition.isValid()) {
  53412. condition._currentResult = false;
  53413. return;
  53414. }
  53415. condition._currentResult = true;
  53416. }
  53417. }
  53418. this.onBeforeExecuteObservable.notifyObservers(this);
  53419. this._nextActiveAction.execute(evt);
  53420. this.skipToNextActiveAction();
  53421. };
  53422. /**
  53423. * Execute placeholder for child classes
  53424. * @param evt optional action event
  53425. */
  53426. Action.prototype.execute = function (evt) {
  53427. };
  53428. /**
  53429. * Skips to next active action
  53430. */
  53431. Action.prototype.skipToNextActiveAction = function () {
  53432. if (this._nextActiveAction._child) {
  53433. if (!this._nextActiveAction._child._actionManager) {
  53434. this._nextActiveAction._child._actionManager = this._actionManager;
  53435. }
  53436. this._nextActiveAction = this._nextActiveAction._child;
  53437. }
  53438. else {
  53439. this._nextActiveAction = this;
  53440. }
  53441. };
  53442. /**
  53443. * Adds action to chain of actions, may be a DoNothingAction
  53444. * @param action defines the next action to execute
  53445. * @returns The action passed in
  53446. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53447. */
  53448. Action.prototype.then = function (action) {
  53449. this._child = action;
  53450. action._actionManager = this._actionManager;
  53451. action._prepare();
  53452. return action;
  53453. };
  53454. /**
  53455. * Internal only
  53456. * @hidden
  53457. */
  53458. Action.prototype._getProperty = function (propertyPath) {
  53459. return this._actionManager._getProperty(propertyPath);
  53460. };
  53461. /**
  53462. * Internal only
  53463. * @hidden
  53464. */
  53465. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53466. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53467. };
  53468. /**
  53469. * Serialize placeholder for child classes
  53470. * @param parent of child
  53471. * @returns the serialized object
  53472. */
  53473. Action.prototype.serialize = function (parent) {
  53474. };
  53475. /**
  53476. * Internal only called by serialize
  53477. * @hidden
  53478. */
  53479. Action.prototype._serialize = function (serializedAction, parent) {
  53480. var serializationObject = {
  53481. type: 1,
  53482. children: [],
  53483. name: serializedAction.name,
  53484. properties: serializedAction.properties || []
  53485. };
  53486. // Serialize child
  53487. if (this._child) {
  53488. this._child.serialize(serializationObject);
  53489. }
  53490. // Check if "this" has a condition
  53491. if (this._condition) {
  53492. var serializedCondition = this._condition.serialize();
  53493. serializedCondition.children.push(serializationObject);
  53494. if (parent) {
  53495. parent.children.push(serializedCondition);
  53496. }
  53497. return serializedCondition;
  53498. }
  53499. if (parent) {
  53500. parent.children.push(serializationObject);
  53501. }
  53502. return serializationObject;
  53503. };
  53504. /**
  53505. * Internal only
  53506. * @hidden
  53507. */
  53508. Action._SerializeValueAsString = function (value) {
  53509. if (typeof value === "number") {
  53510. return value.toString();
  53511. }
  53512. if (typeof value === "boolean") {
  53513. return value ? "true" : "false";
  53514. }
  53515. if (value instanceof BABYLON.Vector2) {
  53516. return value.x + ", " + value.y;
  53517. }
  53518. if (value instanceof BABYLON.Vector3) {
  53519. return value.x + ", " + value.y + ", " + value.z;
  53520. }
  53521. if (value instanceof BABYLON.Color3) {
  53522. return value.r + ", " + value.g + ", " + value.b;
  53523. }
  53524. if (value instanceof BABYLON.Color4) {
  53525. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53526. }
  53527. return value; // string
  53528. };
  53529. /**
  53530. * Internal only
  53531. * @hidden
  53532. */
  53533. Action._GetTargetProperty = function (target) {
  53534. return {
  53535. name: "target",
  53536. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53537. : target instanceof BABYLON.Light ? "LightProperties"
  53538. : target instanceof BABYLON.Camera ? "CameraProperties"
  53539. : "SceneProperties",
  53540. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53541. };
  53542. };
  53543. return Action;
  53544. }());
  53545. BABYLON.Action = Action;
  53546. })(BABYLON || (BABYLON = {}));
  53547. //# sourceMappingURL=babylon.action.js.map
  53548. var BABYLON;
  53549. (function (BABYLON) {
  53550. /**
  53551. * ActionEvent is the event being sent when an action is triggered.
  53552. */
  53553. var ActionEvent = /** @class */ (function () {
  53554. /**
  53555. * Creates a new ActionEvent
  53556. * @param source The mesh or sprite that triggered the action
  53557. * @param pointerX The X mouse cursor position at the time of the event
  53558. * @param pointerY The Y mouse cursor position at the time of the event
  53559. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53560. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53561. * @param additionalData additional data for the event
  53562. */
  53563. function ActionEvent(
  53564. /** The mesh or sprite that triggered the action */
  53565. source,
  53566. /** The X mouse cursor position at the time of the event */
  53567. pointerX,
  53568. /** The Y mouse cursor position at the time of the event */
  53569. pointerY,
  53570. /** The mesh that is currently pointed at (can be null) */
  53571. meshUnderPointer,
  53572. /** the original (browser) event that triggered the ActionEvent */
  53573. sourceEvent,
  53574. /** additional data for the event */
  53575. additionalData) {
  53576. this.source = source;
  53577. this.pointerX = pointerX;
  53578. this.pointerY = pointerY;
  53579. this.meshUnderPointer = meshUnderPointer;
  53580. this.sourceEvent = sourceEvent;
  53581. this.additionalData = additionalData;
  53582. }
  53583. /**
  53584. * Helper function to auto-create an ActionEvent from a source mesh.
  53585. * @param source The source mesh that triggered the event
  53586. * @param evt The original (browser) event
  53587. * @param additionalData additional data for the event
  53588. * @returns the new ActionEvent
  53589. */
  53590. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53591. var scene = source.getScene();
  53592. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53593. };
  53594. /**
  53595. * Helper function to auto-create an ActionEvent from a source sprite
  53596. * @param source The source sprite that triggered the event
  53597. * @param scene Scene associated with the sprite
  53598. * @param evt The original (browser) event
  53599. * @param additionalData additional data for the event
  53600. * @returns the new ActionEvent
  53601. */
  53602. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53603. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53604. };
  53605. /**
  53606. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53607. * @param scene the scene where the event occurred
  53608. * @param evt The original (browser) event
  53609. * @returns the new ActionEvent
  53610. */
  53611. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53612. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53613. };
  53614. /**
  53615. * Helper function to auto-create an ActionEvent from a primitive
  53616. * @param prim defines the target primitive
  53617. * @param pointerPos defines the pointer position
  53618. * @param evt The original (browser) event
  53619. * @param additionalData additional data for the event
  53620. * @returns the new ActionEvent
  53621. */
  53622. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53623. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53624. };
  53625. return ActionEvent;
  53626. }());
  53627. BABYLON.ActionEvent = ActionEvent;
  53628. /**
  53629. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53630. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53631. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53632. */
  53633. var ActionManager = /** @class */ (function () {
  53634. /**
  53635. * Creates a new action manager
  53636. * @param scene defines the hosting scene
  53637. */
  53638. function ActionManager(scene) {
  53639. // Members
  53640. /** Gets the list of actions */
  53641. this.actions = new Array();
  53642. /** Gets the cursor to use when hovering items */
  53643. this.hoverCursor = '';
  53644. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53645. scene._actionManagers.push(this);
  53646. }
  53647. Object.defineProperty(ActionManager, "NothingTrigger", {
  53648. /**
  53649. * Nothing
  53650. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53651. */
  53652. get: function () {
  53653. return ActionManager._NothingTrigger;
  53654. },
  53655. enumerable: true,
  53656. configurable: true
  53657. });
  53658. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53659. /**
  53660. * On pick
  53661. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53662. */
  53663. get: function () {
  53664. return ActionManager._OnPickTrigger;
  53665. },
  53666. enumerable: true,
  53667. configurable: true
  53668. });
  53669. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53670. /**
  53671. * On left pick
  53672. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53673. */
  53674. get: function () {
  53675. return ActionManager._OnLeftPickTrigger;
  53676. },
  53677. enumerable: true,
  53678. configurable: true
  53679. });
  53680. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53681. /**
  53682. * On right pick
  53683. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53684. */
  53685. get: function () {
  53686. return ActionManager._OnRightPickTrigger;
  53687. },
  53688. enumerable: true,
  53689. configurable: true
  53690. });
  53691. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53692. /**
  53693. * On center pick
  53694. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53695. */
  53696. get: function () {
  53697. return ActionManager._OnCenterPickTrigger;
  53698. },
  53699. enumerable: true,
  53700. configurable: true
  53701. });
  53702. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53703. /**
  53704. * On pick down
  53705. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53706. */
  53707. get: function () {
  53708. return ActionManager._OnPickDownTrigger;
  53709. },
  53710. enumerable: true,
  53711. configurable: true
  53712. });
  53713. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53714. /**
  53715. * On double pick
  53716. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53717. */
  53718. get: function () {
  53719. return ActionManager._OnDoublePickTrigger;
  53720. },
  53721. enumerable: true,
  53722. configurable: true
  53723. });
  53724. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53725. /**
  53726. * On pick up
  53727. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53728. */
  53729. get: function () {
  53730. return ActionManager._OnPickUpTrigger;
  53731. },
  53732. enumerable: true,
  53733. configurable: true
  53734. });
  53735. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53736. /**
  53737. * On pick out.
  53738. * This trigger will only be raised if you also declared a OnPickDown
  53739. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53740. */
  53741. get: function () {
  53742. return ActionManager._OnPickOutTrigger;
  53743. },
  53744. enumerable: true,
  53745. configurable: true
  53746. });
  53747. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53748. /**
  53749. * On long press
  53750. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53751. */
  53752. get: function () {
  53753. return ActionManager._OnLongPressTrigger;
  53754. },
  53755. enumerable: true,
  53756. configurable: true
  53757. });
  53758. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53759. /**
  53760. * On pointer over
  53761. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53762. */
  53763. get: function () {
  53764. return ActionManager._OnPointerOverTrigger;
  53765. },
  53766. enumerable: true,
  53767. configurable: true
  53768. });
  53769. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53770. /**
  53771. * On pointer out
  53772. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53773. */
  53774. get: function () {
  53775. return ActionManager._OnPointerOutTrigger;
  53776. },
  53777. enumerable: true,
  53778. configurable: true
  53779. });
  53780. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53781. /**
  53782. * On every frame
  53783. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53784. */
  53785. get: function () {
  53786. return ActionManager._OnEveryFrameTrigger;
  53787. },
  53788. enumerable: true,
  53789. configurable: true
  53790. });
  53791. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53792. /**
  53793. * On intersection enter
  53794. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53795. */
  53796. get: function () {
  53797. return ActionManager._OnIntersectionEnterTrigger;
  53798. },
  53799. enumerable: true,
  53800. configurable: true
  53801. });
  53802. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53803. /**
  53804. * On intersection exit
  53805. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53806. */
  53807. get: function () {
  53808. return ActionManager._OnIntersectionExitTrigger;
  53809. },
  53810. enumerable: true,
  53811. configurable: true
  53812. });
  53813. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53814. /**
  53815. * On key down
  53816. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53817. */
  53818. get: function () {
  53819. return ActionManager._OnKeyDownTrigger;
  53820. },
  53821. enumerable: true,
  53822. configurable: true
  53823. });
  53824. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53825. /**
  53826. * On key up
  53827. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53828. */
  53829. get: function () {
  53830. return ActionManager._OnKeyUpTrigger;
  53831. },
  53832. enumerable: true,
  53833. configurable: true
  53834. });
  53835. // Methods
  53836. /**
  53837. * Releases all associated resources
  53838. */
  53839. ActionManager.prototype.dispose = function () {
  53840. var index = this._scene._actionManagers.indexOf(this);
  53841. for (var i = 0; i < this.actions.length; i++) {
  53842. var action = this.actions[i];
  53843. ActionManager.Triggers[action.trigger]--;
  53844. if (ActionManager.Triggers[action.trigger] === 0) {
  53845. delete ActionManager.Triggers[action.trigger];
  53846. }
  53847. }
  53848. if (index > -1) {
  53849. this._scene._actionManagers.splice(index, 1);
  53850. }
  53851. };
  53852. /**
  53853. * Gets hosting scene
  53854. * @returns the hosting scene
  53855. */
  53856. ActionManager.prototype.getScene = function () {
  53857. return this._scene;
  53858. };
  53859. /**
  53860. * Does this action manager handles actions of any of the given triggers
  53861. * @param triggers defines the triggers to be tested
  53862. * @return a boolean indicating whether one (or more) of the triggers is handled
  53863. */
  53864. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53865. for (var index = 0; index < this.actions.length; index++) {
  53866. var action = this.actions[index];
  53867. if (triggers.indexOf(action.trigger) > -1) {
  53868. return true;
  53869. }
  53870. }
  53871. return false;
  53872. };
  53873. /**
  53874. * Does this action manager handles actions of a given trigger
  53875. * @param trigger defines the trigger to be tested
  53876. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53877. * @return whether the trigger is handled
  53878. */
  53879. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53880. for (var index = 0; index < this.actions.length; index++) {
  53881. var action = this.actions[index];
  53882. if (action.trigger === trigger) {
  53883. if (parameterPredicate) {
  53884. if (parameterPredicate(action.getTriggerParameter())) {
  53885. return true;
  53886. }
  53887. }
  53888. else {
  53889. return true;
  53890. }
  53891. }
  53892. }
  53893. return false;
  53894. };
  53895. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53896. /**
  53897. * Does this action manager has pointer triggers
  53898. */
  53899. get: function () {
  53900. for (var index = 0; index < this.actions.length; index++) {
  53901. var action = this.actions[index];
  53902. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53903. return true;
  53904. }
  53905. }
  53906. return false;
  53907. },
  53908. enumerable: true,
  53909. configurable: true
  53910. });
  53911. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53912. /**
  53913. * Does this action manager has pick triggers
  53914. */
  53915. get: function () {
  53916. for (var index = 0; index < this.actions.length; index++) {
  53917. var action = this.actions[index];
  53918. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53919. return true;
  53920. }
  53921. }
  53922. return false;
  53923. },
  53924. enumerable: true,
  53925. configurable: true
  53926. });
  53927. Object.defineProperty(ActionManager, "HasTriggers", {
  53928. /**
  53929. * Does exist one action manager with at least one trigger
  53930. **/
  53931. get: function () {
  53932. for (var t in ActionManager.Triggers) {
  53933. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53934. return true;
  53935. }
  53936. }
  53937. return false;
  53938. },
  53939. enumerable: true,
  53940. configurable: true
  53941. });
  53942. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53943. /**
  53944. * Does exist one action manager with at least one pick trigger
  53945. **/
  53946. get: function () {
  53947. for (var t in ActionManager.Triggers) {
  53948. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53949. var t_int = parseInt(t);
  53950. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53951. return true;
  53952. }
  53953. }
  53954. }
  53955. return false;
  53956. },
  53957. enumerable: true,
  53958. configurable: true
  53959. });
  53960. /**
  53961. * Does exist one action manager that handles actions of a given trigger
  53962. * @param trigger defines the trigger to be tested
  53963. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53964. **/
  53965. ActionManager.HasSpecificTrigger = function (trigger) {
  53966. for (var t in ActionManager.Triggers) {
  53967. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53968. var t_int = parseInt(t);
  53969. if (t_int === trigger) {
  53970. return true;
  53971. }
  53972. }
  53973. }
  53974. return false;
  53975. };
  53976. /**
  53977. * Registers an action to this action manager
  53978. * @param action defines the action to be registered
  53979. * @return the action amended (prepared) after registration
  53980. */
  53981. ActionManager.prototype.registerAction = function (action) {
  53982. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53983. if (this.getScene().actionManager !== this) {
  53984. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53985. return null;
  53986. }
  53987. }
  53988. this.actions.push(action);
  53989. if (ActionManager.Triggers[action.trigger]) {
  53990. ActionManager.Triggers[action.trigger]++;
  53991. }
  53992. else {
  53993. ActionManager.Triggers[action.trigger] = 1;
  53994. }
  53995. action._actionManager = this;
  53996. action._prepare();
  53997. return action;
  53998. };
  53999. /**
  54000. * Unregisters an action to this action manager
  54001. * @param action defines the action to be unregistered
  54002. * @return a boolean indicating whether the action has been unregistered
  54003. */
  54004. ActionManager.prototype.unregisterAction = function (action) {
  54005. var index = this.actions.indexOf(action);
  54006. if (index !== -1) {
  54007. this.actions.splice(index, 1);
  54008. ActionManager.Triggers[action.trigger] -= 1;
  54009. if (ActionManager.Triggers[action.trigger] === 0) {
  54010. delete ActionManager.Triggers[action.trigger];
  54011. }
  54012. delete action._actionManager;
  54013. return true;
  54014. }
  54015. return false;
  54016. };
  54017. /**
  54018. * Process a specific trigger
  54019. * @param trigger defines the trigger to process
  54020. * @param evt defines the event details to be processed
  54021. */
  54022. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54023. for (var index = 0; index < this.actions.length; index++) {
  54024. var action = this.actions[index];
  54025. if (action.trigger === trigger) {
  54026. if (evt) {
  54027. if (trigger === ActionManager.OnKeyUpTrigger
  54028. || trigger === ActionManager.OnKeyDownTrigger) {
  54029. var parameter = action.getTriggerParameter();
  54030. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54031. if (!parameter.toLowerCase) {
  54032. continue;
  54033. }
  54034. var lowerCase = parameter.toLowerCase();
  54035. if (lowerCase !== evt.sourceEvent.key) {
  54036. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54037. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54038. if (actualkey !== lowerCase) {
  54039. continue;
  54040. }
  54041. }
  54042. }
  54043. }
  54044. }
  54045. action._executeCurrent(evt);
  54046. }
  54047. }
  54048. };
  54049. /** @hidden */
  54050. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54051. var properties = propertyPath.split(".");
  54052. for (var index = 0; index < properties.length - 1; index++) {
  54053. target = target[properties[index]];
  54054. }
  54055. return target;
  54056. };
  54057. /** @hidden */
  54058. ActionManager.prototype._getProperty = function (propertyPath) {
  54059. var properties = propertyPath.split(".");
  54060. return properties[properties.length - 1];
  54061. };
  54062. /**
  54063. * Serialize this manager to a JSON object
  54064. * @param name defines the property name to store this manager
  54065. * @returns a JSON representation of this manager
  54066. */
  54067. ActionManager.prototype.serialize = function (name) {
  54068. var root = {
  54069. children: new Array(),
  54070. name: name,
  54071. type: 3,
  54072. properties: new Array() // Empty for root but required
  54073. };
  54074. for (var i = 0; i < this.actions.length; i++) {
  54075. var triggerObject = {
  54076. type: 0,
  54077. children: new Array(),
  54078. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54079. properties: new Array()
  54080. };
  54081. var triggerOptions = this.actions[i].triggerOptions;
  54082. if (triggerOptions && typeof triggerOptions !== "number") {
  54083. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54084. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54085. }
  54086. else {
  54087. var parameter = {};
  54088. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54089. if (triggerOptions.parameter.mesh) {
  54090. parameter._meshId = triggerOptions.parameter.mesh.id;
  54091. }
  54092. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54093. }
  54094. }
  54095. // Serialize child action, recursively
  54096. this.actions[i].serialize(triggerObject);
  54097. // Add serialized trigger
  54098. root.children.push(triggerObject);
  54099. }
  54100. return root;
  54101. };
  54102. /**
  54103. * Creates a new ActionManager from a JSON data
  54104. * @param parsedActions defines the JSON data to read from
  54105. * @param object defines the hosting mesh
  54106. * @param scene defines the hosting scene
  54107. */
  54108. ActionManager.Parse = function (parsedActions, object, scene) {
  54109. var actionManager = new ActionManager(scene);
  54110. if (object === null)
  54111. scene.actionManager = actionManager;
  54112. else
  54113. object.actionManager = actionManager;
  54114. // instanciate a new object
  54115. var instanciate = function (name, params) {
  54116. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54117. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54118. newInstance.constructor.apply(newInstance, params);
  54119. return newInstance;
  54120. };
  54121. var parseParameter = function (name, value, target, propertyPath) {
  54122. if (propertyPath === null) {
  54123. // String, boolean or float
  54124. var floatValue = parseFloat(value);
  54125. if (value === "true" || value === "false")
  54126. return value === "true";
  54127. else
  54128. return isNaN(floatValue) ? value : floatValue;
  54129. }
  54130. var effectiveTarget = propertyPath.split(".");
  54131. var values = value.split(",");
  54132. // Get effective Target
  54133. for (var i = 0; i < effectiveTarget.length; i++) {
  54134. target = target[effectiveTarget[i]];
  54135. }
  54136. // Return appropriate value with its type
  54137. if (typeof (target) === "boolean")
  54138. return values[0] === "true";
  54139. if (typeof (target) === "string")
  54140. return values[0];
  54141. // Parameters with multiple values such as Vector3 etc.
  54142. var split = new Array();
  54143. for (var i = 0; i < values.length; i++)
  54144. split.push(parseFloat(values[i]));
  54145. if (target instanceof BABYLON.Vector3)
  54146. return BABYLON.Vector3.FromArray(split);
  54147. if (target instanceof BABYLON.Vector4)
  54148. return BABYLON.Vector4.FromArray(split);
  54149. if (target instanceof BABYLON.Color3)
  54150. return BABYLON.Color3.FromArray(split);
  54151. if (target instanceof BABYLON.Color4)
  54152. return BABYLON.Color4.FromArray(split);
  54153. return parseFloat(values[0]);
  54154. };
  54155. // traverse graph per trigger
  54156. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54157. if (combineArray === void 0) { combineArray = null; }
  54158. if (parsedAction.detached)
  54159. return;
  54160. var parameters = new Array();
  54161. var target = null;
  54162. var propertyPath = null;
  54163. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54164. // Parameters
  54165. if (parsedAction.type === 2)
  54166. parameters.push(actionManager);
  54167. else
  54168. parameters.push(trigger);
  54169. if (combine) {
  54170. var actions = new Array();
  54171. for (var j = 0; j < parsedAction.combine.length; j++) {
  54172. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54173. }
  54174. parameters.push(actions);
  54175. }
  54176. else {
  54177. for (var i = 0; i < parsedAction.properties.length; i++) {
  54178. var value = parsedAction.properties[i].value;
  54179. var name = parsedAction.properties[i].name;
  54180. var targetType = parsedAction.properties[i].targetType;
  54181. if (name === "target")
  54182. if (targetType !== null && targetType === "SceneProperties")
  54183. value = target = scene;
  54184. else
  54185. value = target = scene.getNodeByName(value);
  54186. else if (name === "parent")
  54187. value = scene.getNodeByName(value);
  54188. else if (name === "sound")
  54189. value = scene.getSoundByName(value);
  54190. else if (name !== "propertyPath") {
  54191. if (parsedAction.type === 2 && name === "operator")
  54192. value = BABYLON.ValueCondition[value];
  54193. else
  54194. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54195. }
  54196. else {
  54197. propertyPath = value;
  54198. }
  54199. parameters.push(value);
  54200. }
  54201. }
  54202. if (combineArray === null) {
  54203. parameters.push(condition);
  54204. }
  54205. else {
  54206. parameters.push(null);
  54207. }
  54208. // If interpolate value action
  54209. if (parsedAction.name === "InterpolateValueAction") {
  54210. var param = parameters[parameters.length - 2];
  54211. parameters[parameters.length - 1] = param;
  54212. parameters[parameters.length - 2] = condition;
  54213. }
  54214. // Action or condition(s) and not CombineAction
  54215. var newAction = instanciate(parsedAction.name, parameters);
  54216. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54217. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54218. if (action)
  54219. action.then(nothing);
  54220. else
  54221. actionManager.registerAction(nothing);
  54222. action = nothing;
  54223. }
  54224. if (combineArray === null) {
  54225. if (newAction instanceof BABYLON.Condition) {
  54226. condition = newAction;
  54227. newAction = action;
  54228. }
  54229. else {
  54230. condition = null;
  54231. if (action)
  54232. action.then(newAction);
  54233. else
  54234. actionManager.registerAction(newAction);
  54235. }
  54236. }
  54237. else {
  54238. combineArray.push(newAction);
  54239. }
  54240. for (var i = 0; i < parsedAction.children.length; i++)
  54241. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54242. };
  54243. // triggers
  54244. for (var i = 0; i < parsedActions.children.length; i++) {
  54245. var triggerParams;
  54246. var trigger = parsedActions.children[i];
  54247. if (trigger.properties.length > 0) {
  54248. var param = trigger.properties[0].value;
  54249. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54250. if (value._meshId) {
  54251. value.mesh = scene.getMeshByID(value._meshId);
  54252. }
  54253. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54254. }
  54255. else
  54256. triggerParams = ActionManager[trigger.name];
  54257. for (var j = 0; j < trigger.children.length; j++) {
  54258. if (!trigger.detached)
  54259. traverse(trigger.children[j], triggerParams, null, null);
  54260. }
  54261. }
  54262. };
  54263. /**
  54264. * Get a trigger name by index
  54265. * @param trigger defines the trigger index
  54266. * @returns a trigger name
  54267. */
  54268. ActionManager.GetTriggerName = function (trigger) {
  54269. switch (trigger) {
  54270. case 0: return "NothingTrigger";
  54271. case 1: return "OnPickTrigger";
  54272. case 2: return "OnLeftPickTrigger";
  54273. case 3: return "OnRightPickTrigger";
  54274. case 4: return "OnCenterPickTrigger";
  54275. case 5: return "OnPickDownTrigger";
  54276. case 6: return "OnPickUpTrigger";
  54277. case 7: return "OnLongPressTrigger";
  54278. case 8: return "OnPointerOverTrigger";
  54279. case 9: return "OnPointerOutTrigger";
  54280. case 10: return "OnEveryFrameTrigger";
  54281. case 11: return "OnIntersectionEnterTrigger";
  54282. case 12: return "OnIntersectionExitTrigger";
  54283. case 13: return "OnKeyDownTrigger";
  54284. case 14: return "OnKeyUpTrigger";
  54285. case 15: return "OnPickOutTrigger";
  54286. default: return "";
  54287. }
  54288. };
  54289. // Statics
  54290. ActionManager._NothingTrigger = 0;
  54291. ActionManager._OnPickTrigger = 1;
  54292. ActionManager._OnLeftPickTrigger = 2;
  54293. ActionManager._OnRightPickTrigger = 3;
  54294. ActionManager._OnCenterPickTrigger = 4;
  54295. ActionManager._OnPickDownTrigger = 5;
  54296. ActionManager._OnDoublePickTrigger = 6;
  54297. ActionManager._OnPickUpTrigger = 7;
  54298. ActionManager._OnLongPressTrigger = 8;
  54299. ActionManager._OnPointerOverTrigger = 9;
  54300. ActionManager._OnPointerOutTrigger = 10;
  54301. ActionManager._OnEveryFrameTrigger = 11;
  54302. ActionManager._OnIntersectionEnterTrigger = 12;
  54303. ActionManager._OnIntersectionExitTrigger = 13;
  54304. ActionManager._OnKeyDownTrigger = 14;
  54305. ActionManager._OnKeyUpTrigger = 15;
  54306. ActionManager._OnPickOutTrigger = 16;
  54307. /** Gets the list of active triggers */
  54308. ActionManager.Triggers = {};
  54309. return ActionManager;
  54310. }());
  54311. BABYLON.ActionManager = ActionManager;
  54312. })(BABYLON || (BABYLON = {}));
  54313. //# sourceMappingURL=babylon.actionManager.js.map
  54314. var BABYLON;
  54315. (function (BABYLON) {
  54316. var InterpolateValueAction = /** @class */ (function (_super) {
  54317. __extends(InterpolateValueAction, _super);
  54318. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54319. if (duration === void 0) { duration = 1000; }
  54320. var _this = _super.call(this, triggerOptions, condition) || this;
  54321. _this.propertyPath = propertyPath;
  54322. _this.value = value;
  54323. _this.duration = duration;
  54324. _this.stopOtherAnimations = stopOtherAnimations;
  54325. _this.onInterpolationDone = onInterpolationDone;
  54326. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54327. _this._target = _this._effectiveTarget = target;
  54328. return _this;
  54329. }
  54330. InterpolateValueAction.prototype._prepare = function () {
  54331. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54332. this._property = this._getProperty(this.propertyPath);
  54333. };
  54334. InterpolateValueAction.prototype.execute = function () {
  54335. var _this = this;
  54336. var scene = this._actionManager.getScene();
  54337. var keys = [
  54338. {
  54339. frame: 0,
  54340. value: this._effectiveTarget[this._property]
  54341. }, {
  54342. frame: 100,
  54343. value: this.value
  54344. }
  54345. ];
  54346. var dataType;
  54347. if (typeof this.value === "number") {
  54348. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54349. }
  54350. else if (this.value instanceof BABYLON.Color3) {
  54351. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54352. }
  54353. else if (this.value instanceof BABYLON.Vector3) {
  54354. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54355. }
  54356. else if (this.value instanceof BABYLON.Matrix) {
  54357. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54358. }
  54359. else if (this.value instanceof BABYLON.Quaternion) {
  54360. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54361. }
  54362. else {
  54363. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54364. return;
  54365. }
  54366. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54367. animation.setKeys(keys);
  54368. if (this.stopOtherAnimations) {
  54369. scene.stopAnimation(this._effectiveTarget);
  54370. }
  54371. var wrapper = function () {
  54372. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54373. if (_this.onInterpolationDone) {
  54374. _this.onInterpolationDone();
  54375. }
  54376. };
  54377. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54378. };
  54379. InterpolateValueAction.prototype.serialize = function (parent) {
  54380. return _super.prototype._serialize.call(this, {
  54381. name: "InterpolateValueAction",
  54382. properties: [
  54383. BABYLON.Action._GetTargetProperty(this._target),
  54384. { name: "propertyPath", value: this.propertyPath },
  54385. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54386. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54387. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54388. ]
  54389. }, parent);
  54390. };
  54391. return InterpolateValueAction;
  54392. }(BABYLON.Action));
  54393. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54394. })(BABYLON || (BABYLON = {}));
  54395. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54396. var BABYLON;
  54397. (function (BABYLON) {
  54398. var SwitchBooleanAction = /** @class */ (function (_super) {
  54399. __extends(SwitchBooleanAction, _super);
  54400. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54401. var _this = _super.call(this, triggerOptions, condition) || this;
  54402. _this.propertyPath = propertyPath;
  54403. _this._target = _this._effectiveTarget = target;
  54404. return _this;
  54405. }
  54406. SwitchBooleanAction.prototype._prepare = function () {
  54407. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54408. this._property = this._getProperty(this.propertyPath);
  54409. };
  54410. SwitchBooleanAction.prototype.execute = function () {
  54411. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54412. };
  54413. SwitchBooleanAction.prototype.serialize = function (parent) {
  54414. return _super.prototype._serialize.call(this, {
  54415. name: "SwitchBooleanAction",
  54416. properties: [
  54417. BABYLON.Action._GetTargetProperty(this._target),
  54418. { name: "propertyPath", value: this.propertyPath }
  54419. ]
  54420. }, parent);
  54421. };
  54422. return SwitchBooleanAction;
  54423. }(BABYLON.Action));
  54424. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54425. var SetStateAction = /** @class */ (function (_super) {
  54426. __extends(SetStateAction, _super);
  54427. function SetStateAction(triggerOptions, target, value, condition) {
  54428. var _this = _super.call(this, triggerOptions, condition) || this;
  54429. _this.value = value;
  54430. _this._target = target;
  54431. return _this;
  54432. }
  54433. SetStateAction.prototype.execute = function () {
  54434. this._target.state = this.value;
  54435. };
  54436. SetStateAction.prototype.serialize = function (parent) {
  54437. return _super.prototype._serialize.call(this, {
  54438. name: "SetStateAction",
  54439. properties: [
  54440. BABYLON.Action._GetTargetProperty(this._target),
  54441. { name: "value", value: this.value }
  54442. ]
  54443. }, parent);
  54444. };
  54445. return SetStateAction;
  54446. }(BABYLON.Action));
  54447. BABYLON.SetStateAction = SetStateAction;
  54448. var SetValueAction = /** @class */ (function (_super) {
  54449. __extends(SetValueAction, _super);
  54450. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54451. var _this = _super.call(this, triggerOptions, condition) || this;
  54452. _this.propertyPath = propertyPath;
  54453. _this.value = value;
  54454. _this._target = _this._effectiveTarget = target;
  54455. return _this;
  54456. }
  54457. SetValueAction.prototype._prepare = function () {
  54458. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54459. this._property = this._getProperty(this.propertyPath);
  54460. };
  54461. SetValueAction.prototype.execute = function () {
  54462. this._effectiveTarget[this._property] = this.value;
  54463. if (this._target.markAsDirty) {
  54464. this._target.markAsDirty(this._property);
  54465. }
  54466. };
  54467. SetValueAction.prototype.serialize = function (parent) {
  54468. return _super.prototype._serialize.call(this, {
  54469. name: "SetValueAction",
  54470. properties: [
  54471. BABYLON.Action._GetTargetProperty(this._target),
  54472. { name: "propertyPath", value: this.propertyPath },
  54473. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54474. ]
  54475. }, parent);
  54476. };
  54477. return SetValueAction;
  54478. }(BABYLON.Action));
  54479. BABYLON.SetValueAction = SetValueAction;
  54480. var IncrementValueAction = /** @class */ (function (_super) {
  54481. __extends(IncrementValueAction, _super);
  54482. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54483. var _this = _super.call(this, triggerOptions, condition) || this;
  54484. _this.propertyPath = propertyPath;
  54485. _this.value = value;
  54486. _this._target = _this._effectiveTarget = target;
  54487. return _this;
  54488. }
  54489. IncrementValueAction.prototype._prepare = function () {
  54490. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54491. this._property = this._getProperty(this.propertyPath);
  54492. if (typeof this._effectiveTarget[this._property] !== "number") {
  54493. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54494. }
  54495. };
  54496. IncrementValueAction.prototype.execute = function () {
  54497. this._effectiveTarget[this._property] += this.value;
  54498. if (this._target.markAsDirty) {
  54499. this._target.markAsDirty(this._property);
  54500. }
  54501. };
  54502. IncrementValueAction.prototype.serialize = function (parent) {
  54503. return _super.prototype._serialize.call(this, {
  54504. name: "IncrementValueAction",
  54505. properties: [
  54506. BABYLON.Action._GetTargetProperty(this._target),
  54507. { name: "propertyPath", value: this.propertyPath },
  54508. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54509. ]
  54510. }, parent);
  54511. };
  54512. return IncrementValueAction;
  54513. }(BABYLON.Action));
  54514. BABYLON.IncrementValueAction = IncrementValueAction;
  54515. var PlayAnimationAction = /** @class */ (function (_super) {
  54516. __extends(PlayAnimationAction, _super);
  54517. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54518. var _this = _super.call(this, triggerOptions, condition) || this;
  54519. _this.from = from;
  54520. _this.to = to;
  54521. _this.loop = loop;
  54522. _this._target = target;
  54523. return _this;
  54524. }
  54525. PlayAnimationAction.prototype._prepare = function () {
  54526. };
  54527. PlayAnimationAction.prototype.execute = function () {
  54528. var scene = this._actionManager.getScene();
  54529. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54530. };
  54531. PlayAnimationAction.prototype.serialize = function (parent) {
  54532. return _super.prototype._serialize.call(this, {
  54533. name: "PlayAnimationAction",
  54534. properties: [
  54535. BABYLON.Action._GetTargetProperty(this._target),
  54536. { name: "from", value: String(this.from) },
  54537. { name: "to", value: String(this.to) },
  54538. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54539. ]
  54540. }, parent);
  54541. };
  54542. return PlayAnimationAction;
  54543. }(BABYLON.Action));
  54544. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54545. var StopAnimationAction = /** @class */ (function (_super) {
  54546. __extends(StopAnimationAction, _super);
  54547. function StopAnimationAction(triggerOptions, target, condition) {
  54548. var _this = _super.call(this, triggerOptions, condition) || this;
  54549. _this._target = target;
  54550. return _this;
  54551. }
  54552. StopAnimationAction.prototype._prepare = function () {
  54553. };
  54554. StopAnimationAction.prototype.execute = function () {
  54555. var scene = this._actionManager.getScene();
  54556. scene.stopAnimation(this._target);
  54557. };
  54558. StopAnimationAction.prototype.serialize = function (parent) {
  54559. return _super.prototype._serialize.call(this, {
  54560. name: "StopAnimationAction",
  54561. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54562. }, parent);
  54563. };
  54564. return StopAnimationAction;
  54565. }(BABYLON.Action));
  54566. BABYLON.StopAnimationAction = StopAnimationAction;
  54567. var DoNothingAction = /** @class */ (function (_super) {
  54568. __extends(DoNothingAction, _super);
  54569. function DoNothingAction(triggerOptions, condition) {
  54570. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54571. return _super.call(this, triggerOptions, condition) || this;
  54572. }
  54573. DoNothingAction.prototype.execute = function () {
  54574. };
  54575. DoNothingAction.prototype.serialize = function (parent) {
  54576. return _super.prototype._serialize.call(this, {
  54577. name: "DoNothingAction",
  54578. properties: []
  54579. }, parent);
  54580. };
  54581. return DoNothingAction;
  54582. }(BABYLON.Action));
  54583. BABYLON.DoNothingAction = DoNothingAction;
  54584. var CombineAction = /** @class */ (function (_super) {
  54585. __extends(CombineAction, _super);
  54586. function CombineAction(triggerOptions, children, condition) {
  54587. var _this = _super.call(this, triggerOptions, condition) || this;
  54588. _this.children = children;
  54589. return _this;
  54590. }
  54591. CombineAction.prototype._prepare = function () {
  54592. for (var index = 0; index < this.children.length; index++) {
  54593. this.children[index]._actionManager = this._actionManager;
  54594. this.children[index]._prepare();
  54595. }
  54596. };
  54597. CombineAction.prototype.execute = function (evt) {
  54598. for (var index = 0; index < this.children.length; index++) {
  54599. this.children[index].execute(evt);
  54600. }
  54601. };
  54602. CombineAction.prototype.serialize = function (parent) {
  54603. var serializationObject = _super.prototype._serialize.call(this, {
  54604. name: "CombineAction",
  54605. properties: [],
  54606. combine: []
  54607. }, parent);
  54608. for (var i = 0; i < this.children.length; i++) {
  54609. serializationObject.combine.push(this.children[i].serialize(null));
  54610. }
  54611. return serializationObject;
  54612. };
  54613. return CombineAction;
  54614. }(BABYLON.Action));
  54615. BABYLON.CombineAction = CombineAction;
  54616. var ExecuteCodeAction = /** @class */ (function (_super) {
  54617. __extends(ExecuteCodeAction, _super);
  54618. function ExecuteCodeAction(triggerOptions, func, condition) {
  54619. var _this = _super.call(this, triggerOptions, condition) || this;
  54620. _this.func = func;
  54621. return _this;
  54622. }
  54623. ExecuteCodeAction.prototype.execute = function (evt) {
  54624. this.func(evt);
  54625. };
  54626. return ExecuteCodeAction;
  54627. }(BABYLON.Action));
  54628. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54629. var SetParentAction = /** @class */ (function (_super) {
  54630. __extends(SetParentAction, _super);
  54631. function SetParentAction(triggerOptions, target, parent, condition) {
  54632. var _this = _super.call(this, triggerOptions, condition) || this;
  54633. _this._target = target;
  54634. _this._parent = parent;
  54635. return _this;
  54636. }
  54637. SetParentAction.prototype._prepare = function () {
  54638. };
  54639. SetParentAction.prototype.execute = function () {
  54640. if (this._target.parent === this._parent) {
  54641. return;
  54642. }
  54643. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54644. invertParentWorldMatrix.invert();
  54645. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54646. this._target.parent = this._parent;
  54647. };
  54648. SetParentAction.prototype.serialize = function (parent) {
  54649. return _super.prototype._serialize.call(this, {
  54650. name: "SetParentAction",
  54651. properties: [
  54652. BABYLON.Action._GetTargetProperty(this._target),
  54653. BABYLON.Action._GetTargetProperty(this._parent),
  54654. ]
  54655. }, parent);
  54656. };
  54657. return SetParentAction;
  54658. }(BABYLON.Action));
  54659. BABYLON.SetParentAction = SetParentAction;
  54660. var PlaySoundAction = /** @class */ (function (_super) {
  54661. __extends(PlaySoundAction, _super);
  54662. function PlaySoundAction(triggerOptions, sound, condition) {
  54663. var _this = _super.call(this, triggerOptions, condition) || this;
  54664. _this._sound = sound;
  54665. return _this;
  54666. }
  54667. PlaySoundAction.prototype._prepare = function () {
  54668. };
  54669. PlaySoundAction.prototype.execute = function () {
  54670. if (this._sound !== undefined)
  54671. this._sound.play();
  54672. };
  54673. PlaySoundAction.prototype.serialize = function (parent) {
  54674. return _super.prototype._serialize.call(this, {
  54675. name: "PlaySoundAction",
  54676. properties: [{ name: "sound", value: this._sound.name }]
  54677. }, parent);
  54678. };
  54679. return PlaySoundAction;
  54680. }(BABYLON.Action));
  54681. BABYLON.PlaySoundAction = PlaySoundAction;
  54682. var StopSoundAction = /** @class */ (function (_super) {
  54683. __extends(StopSoundAction, _super);
  54684. function StopSoundAction(triggerOptions, sound, condition) {
  54685. var _this = _super.call(this, triggerOptions, condition) || this;
  54686. _this._sound = sound;
  54687. return _this;
  54688. }
  54689. StopSoundAction.prototype._prepare = function () {
  54690. };
  54691. StopSoundAction.prototype.execute = function () {
  54692. if (this._sound !== undefined)
  54693. this._sound.stop();
  54694. };
  54695. StopSoundAction.prototype.serialize = function (parent) {
  54696. return _super.prototype._serialize.call(this, {
  54697. name: "StopSoundAction",
  54698. properties: [{ name: "sound", value: this._sound.name }]
  54699. }, parent);
  54700. };
  54701. return StopSoundAction;
  54702. }(BABYLON.Action));
  54703. BABYLON.StopSoundAction = StopSoundAction;
  54704. })(BABYLON || (BABYLON = {}));
  54705. //# sourceMappingURL=babylon.directActions.js.map
  54706. var BABYLON;
  54707. (function (BABYLON) {
  54708. var SpriteManager = /** @class */ (function () {
  54709. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54710. if (epsilon === void 0) { epsilon = 0.01; }
  54711. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54712. this.name = name;
  54713. this.sprites = new Array();
  54714. this.renderingGroupId = 0;
  54715. this.layerMask = 0x0FFFFFFF;
  54716. this.fogEnabled = true;
  54717. this.isPickable = false;
  54718. /**
  54719. * An event triggered when the manager is disposed.
  54720. */
  54721. this.onDisposeObservable = new BABYLON.Observable();
  54722. this._vertexBuffers = {};
  54723. this._capacity = capacity;
  54724. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54725. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54726. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54727. if (cellSize.width && cellSize.height) {
  54728. this.cellWidth = cellSize.width;
  54729. this.cellHeight = cellSize.height;
  54730. }
  54731. else if (cellSize !== undefined) {
  54732. this.cellWidth = cellSize;
  54733. this.cellHeight = cellSize;
  54734. }
  54735. else {
  54736. return;
  54737. }
  54738. this._epsilon = epsilon;
  54739. this._scene = scene;
  54740. this._scene.spriteManagers.push(this);
  54741. var indices = [];
  54742. var index = 0;
  54743. for (var count = 0; count < capacity; count++) {
  54744. indices.push(index);
  54745. indices.push(index + 1);
  54746. indices.push(index + 2);
  54747. indices.push(index);
  54748. indices.push(index + 2);
  54749. indices.push(index + 3);
  54750. index += 4;
  54751. }
  54752. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54753. // VBO
  54754. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54755. this._vertexData = new Float32Array(capacity * 16 * 4);
  54756. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54757. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54758. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54759. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54760. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54761. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54762. this._vertexBuffers["options"] = options;
  54763. this._vertexBuffers["cellInfo"] = cellInfo;
  54764. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54765. // Effects
  54766. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54767. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54768. }
  54769. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54770. set: function (callback) {
  54771. if (this._onDisposeObserver) {
  54772. this.onDisposeObservable.remove(this._onDisposeObserver);
  54773. }
  54774. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54775. },
  54776. enumerable: true,
  54777. configurable: true
  54778. });
  54779. Object.defineProperty(SpriteManager.prototype, "texture", {
  54780. get: function () {
  54781. return this._spriteTexture;
  54782. },
  54783. set: function (value) {
  54784. this._spriteTexture = value;
  54785. },
  54786. enumerable: true,
  54787. configurable: true
  54788. });
  54789. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54790. var arrayOffset = index * 16;
  54791. if (offsetX === 0)
  54792. offsetX = this._epsilon;
  54793. else if (offsetX === 1)
  54794. offsetX = 1 - this._epsilon;
  54795. if (offsetY === 0)
  54796. offsetY = this._epsilon;
  54797. else if (offsetY === 1)
  54798. offsetY = 1 - this._epsilon;
  54799. this._vertexData[arrayOffset] = sprite.position.x;
  54800. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54801. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54802. this._vertexData[arrayOffset + 3] = sprite.angle;
  54803. this._vertexData[arrayOffset + 4] = sprite.width;
  54804. this._vertexData[arrayOffset + 5] = sprite.height;
  54805. this._vertexData[arrayOffset + 6] = offsetX;
  54806. this._vertexData[arrayOffset + 7] = offsetY;
  54807. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54808. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54809. var offset = (sprite.cellIndex / rowSize) >> 0;
  54810. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54811. this._vertexData[arrayOffset + 11] = offset;
  54812. // Color
  54813. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54814. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54815. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54816. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54817. };
  54818. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54819. var count = Math.min(this._capacity, this.sprites.length);
  54820. var min = BABYLON.Vector3.Zero();
  54821. var max = BABYLON.Vector3.Zero();
  54822. var distance = Number.MAX_VALUE;
  54823. var currentSprite = null;
  54824. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54825. var cameraView = camera.getViewMatrix();
  54826. for (var index = 0; index < count; index++) {
  54827. var sprite = this.sprites[index];
  54828. if (!sprite) {
  54829. continue;
  54830. }
  54831. if (predicate) {
  54832. if (!predicate(sprite)) {
  54833. continue;
  54834. }
  54835. }
  54836. else if (!sprite.isPickable) {
  54837. continue;
  54838. }
  54839. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54840. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54841. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54842. if (ray.intersectsBoxMinMax(min, max)) {
  54843. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54844. if (distance > currentDistance) {
  54845. distance = currentDistance;
  54846. currentSprite = sprite;
  54847. if (fastCheck) {
  54848. break;
  54849. }
  54850. }
  54851. }
  54852. }
  54853. if (currentSprite) {
  54854. var result = new BABYLON.PickingInfo();
  54855. result.hit = true;
  54856. result.pickedSprite = currentSprite;
  54857. result.distance = distance;
  54858. return result;
  54859. }
  54860. return null;
  54861. };
  54862. SpriteManager.prototype.render = function () {
  54863. // Check
  54864. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54865. return;
  54866. var engine = this._scene.getEngine();
  54867. var baseSize = this._spriteTexture.getBaseSize();
  54868. // Sprites
  54869. var deltaTime = engine.getDeltaTime();
  54870. var max = Math.min(this._capacity, this.sprites.length);
  54871. var rowSize = baseSize.width / this.cellWidth;
  54872. var offset = 0;
  54873. for (var index = 0; index < max; index++) {
  54874. var sprite = this.sprites[index];
  54875. if (!sprite) {
  54876. continue;
  54877. }
  54878. sprite._animate(deltaTime);
  54879. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54880. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54881. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54882. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54883. }
  54884. this._buffer.update(this._vertexData);
  54885. // Render
  54886. var effect = this._effectBase;
  54887. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54888. effect = this._effectFog;
  54889. }
  54890. engine.enableEffect(effect);
  54891. var viewMatrix = this._scene.getViewMatrix();
  54892. effect.setTexture("diffuseSampler", this._spriteTexture);
  54893. effect.setMatrix("view", viewMatrix);
  54894. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54895. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54896. // Fog
  54897. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54898. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54899. effect.setColor3("vFogColor", this._scene.fogColor);
  54900. }
  54901. // VBOs
  54902. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54903. // Draw order
  54904. engine.setDepthFunctionToLessOrEqual();
  54905. effect.setBool("alphaTest", true);
  54906. engine.setColorWrite(false);
  54907. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54908. engine.setColorWrite(true);
  54909. effect.setBool("alphaTest", false);
  54910. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54911. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54912. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54913. };
  54914. SpriteManager.prototype.dispose = function () {
  54915. if (this._buffer) {
  54916. this._buffer.dispose();
  54917. this._buffer = null;
  54918. }
  54919. if (this._indexBuffer) {
  54920. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54921. this._indexBuffer = null;
  54922. }
  54923. if (this._spriteTexture) {
  54924. this._spriteTexture.dispose();
  54925. this._spriteTexture = null;
  54926. }
  54927. // Remove from scene
  54928. var index = this._scene.spriteManagers.indexOf(this);
  54929. this._scene.spriteManagers.splice(index, 1);
  54930. // Callback
  54931. this.onDisposeObservable.notifyObservers(this);
  54932. this.onDisposeObservable.clear();
  54933. };
  54934. return SpriteManager;
  54935. }());
  54936. BABYLON.SpriteManager = SpriteManager;
  54937. })(BABYLON || (BABYLON = {}));
  54938. //# sourceMappingURL=babylon.spriteManager.js.map
  54939. var BABYLON;
  54940. (function (BABYLON) {
  54941. var Sprite = /** @class */ (function () {
  54942. function Sprite(name, manager) {
  54943. this.name = name;
  54944. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54945. this.width = 1.0;
  54946. this.height = 1.0;
  54947. this.angle = 0;
  54948. this.cellIndex = 0;
  54949. this.invertU = 0;
  54950. this.invertV = 0;
  54951. this.animations = new Array();
  54952. this.isPickable = false;
  54953. this._animationStarted = false;
  54954. this._loopAnimation = false;
  54955. this._fromIndex = 0;
  54956. this._toIndex = 0;
  54957. this._delay = 0;
  54958. this._direction = 1;
  54959. this._time = 0;
  54960. this._manager = manager;
  54961. this._manager.sprites.push(this);
  54962. this.position = BABYLON.Vector3.Zero();
  54963. }
  54964. Object.defineProperty(Sprite.prototype, "size", {
  54965. get: function () {
  54966. return this.width;
  54967. },
  54968. set: function (value) {
  54969. this.width = value;
  54970. this.height = value;
  54971. },
  54972. enumerable: true,
  54973. configurable: true
  54974. });
  54975. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54976. this._fromIndex = from;
  54977. this._toIndex = to;
  54978. this._loopAnimation = loop;
  54979. this._delay = delay;
  54980. this._animationStarted = true;
  54981. this._direction = from < to ? 1 : -1;
  54982. this.cellIndex = from;
  54983. this._time = 0;
  54984. this._onAnimationEnd = onAnimationEnd;
  54985. };
  54986. Sprite.prototype.stopAnimation = function () {
  54987. this._animationStarted = false;
  54988. };
  54989. Sprite.prototype._animate = function (deltaTime) {
  54990. if (!this._animationStarted)
  54991. return;
  54992. this._time += deltaTime;
  54993. if (this._time > this._delay) {
  54994. this._time = this._time % this._delay;
  54995. this.cellIndex += this._direction;
  54996. if (this.cellIndex > this._toIndex) {
  54997. if (this._loopAnimation) {
  54998. this.cellIndex = this._fromIndex;
  54999. }
  55000. else {
  55001. this.cellIndex = this._toIndex;
  55002. this._animationStarted = false;
  55003. if (this._onAnimationEnd) {
  55004. this._onAnimationEnd();
  55005. }
  55006. if (this.disposeWhenFinishedAnimating) {
  55007. this.dispose();
  55008. }
  55009. }
  55010. }
  55011. }
  55012. };
  55013. Sprite.prototype.dispose = function () {
  55014. for (var i = 0; i < this._manager.sprites.length; i++) {
  55015. if (this._manager.sprites[i] == this) {
  55016. this._manager.sprites.splice(i, 1);
  55017. }
  55018. }
  55019. };
  55020. return Sprite;
  55021. }());
  55022. BABYLON.Sprite = Sprite;
  55023. })(BABYLON || (BABYLON = {}));
  55024. //# sourceMappingURL=babylon.sprite.js.map
  55025. var BABYLON;
  55026. (function (BABYLON) {
  55027. var IntersectionInfo = /** @class */ (function () {
  55028. function IntersectionInfo(bu, bv, distance) {
  55029. this.bu = bu;
  55030. this.bv = bv;
  55031. this.distance = distance;
  55032. this.faceId = 0;
  55033. this.subMeshId = 0;
  55034. }
  55035. return IntersectionInfo;
  55036. }());
  55037. BABYLON.IntersectionInfo = IntersectionInfo;
  55038. /**
  55039. * Information about the result of picking within a scene
  55040. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55041. */
  55042. var PickingInfo = /** @class */ (function () {
  55043. function PickingInfo() {
  55044. /**
  55045. * If the pick collided with an object
  55046. */
  55047. this.hit = false;
  55048. /**
  55049. * Distance away where the pick collided
  55050. */
  55051. this.distance = 0;
  55052. /**
  55053. * The location of pick collision
  55054. */
  55055. this.pickedPoint = null;
  55056. /**
  55057. * The mesh corrisponding the the pick collision
  55058. */
  55059. this.pickedMesh = null;
  55060. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55061. this.bu = 0;
  55062. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55063. this.bv = 0;
  55064. /** The id of the face on the mesh that was picked */
  55065. this.faceId = -1;
  55066. /** Id of the the submesh that was picked */
  55067. this.subMeshId = 0;
  55068. /** If a sprite was picked, this will be the sprite the pick collided with */
  55069. this.pickedSprite = null;
  55070. /**
  55071. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55072. */
  55073. this.originMesh = null;
  55074. /**
  55075. * The ray that was used to perform the picking.
  55076. */
  55077. this.ray = null;
  55078. }
  55079. /**
  55080. * Gets the normal corrispodning to the face the pick collided with
  55081. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55082. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55083. * @returns The normal corrispodning to the face the pick collided with
  55084. */
  55085. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55086. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55087. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55088. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55089. return null;
  55090. }
  55091. var indices = this.pickedMesh.getIndices();
  55092. if (!indices) {
  55093. return null;
  55094. }
  55095. var result;
  55096. if (useVerticesNormals) {
  55097. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55098. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55099. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55100. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55101. normal0 = normal0.scale(this.bu);
  55102. normal1 = normal1.scale(this.bv);
  55103. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55104. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55105. }
  55106. else {
  55107. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55108. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55109. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55110. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55111. var p1p2 = vertex1.subtract(vertex2);
  55112. var p3p2 = vertex3.subtract(vertex2);
  55113. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55114. }
  55115. if (useWorldCoordinates) {
  55116. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  55117. }
  55118. return BABYLON.Vector3.Normalize(result);
  55119. };
  55120. /**
  55121. * Gets the texture coordinates of where the pick occured
  55122. * @returns the vector containing the coordnates of the texture
  55123. */
  55124. PickingInfo.prototype.getTextureCoordinates = function () {
  55125. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55126. return null;
  55127. }
  55128. var indices = this.pickedMesh.getIndices();
  55129. if (!indices) {
  55130. return null;
  55131. }
  55132. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55133. if (!uvs) {
  55134. return null;
  55135. }
  55136. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55137. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55138. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55139. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55140. uv1 = uv1.scale(this.bu);
  55141. uv2 = uv2.scale(this.bv);
  55142. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55143. };
  55144. return PickingInfo;
  55145. }());
  55146. BABYLON.PickingInfo = PickingInfo;
  55147. })(BABYLON || (BABYLON = {}));
  55148. //# sourceMappingURL=babylon.pickingInfo.js.map
  55149. var BABYLON;
  55150. (function (BABYLON) {
  55151. var Ray = /** @class */ (function () {
  55152. function Ray(origin, direction, length) {
  55153. if (length === void 0) { length = Number.MAX_VALUE; }
  55154. this.origin = origin;
  55155. this.direction = direction;
  55156. this.length = length;
  55157. }
  55158. // Methods
  55159. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55160. var d = 0.0;
  55161. var maxValue = Number.MAX_VALUE;
  55162. var inv;
  55163. var min;
  55164. var max;
  55165. var temp;
  55166. if (Math.abs(this.direction.x) < 0.0000001) {
  55167. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55168. return false;
  55169. }
  55170. }
  55171. else {
  55172. inv = 1.0 / this.direction.x;
  55173. min = (minimum.x - this.origin.x) * inv;
  55174. max = (maximum.x - this.origin.x) * inv;
  55175. if (max === -Infinity) {
  55176. max = Infinity;
  55177. }
  55178. if (min > max) {
  55179. temp = min;
  55180. min = max;
  55181. max = temp;
  55182. }
  55183. d = Math.max(min, d);
  55184. maxValue = Math.min(max, maxValue);
  55185. if (d > maxValue) {
  55186. return false;
  55187. }
  55188. }
  55189. if (Math.abs(this.direction.y) < 0.0000001) {
  55190. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55191. return false;
  55192. }
  55193. }
  55194. else {
  55195. inv = 1.0 / this.direction.y;
  55196. min = (minimum.y - this.origin.y) * inv;
  55197. max = (maximum.y - this.origin.y) * inv;
  55198. if (max === -Infinity) {
  55199. max = Infinity;
  55200. }
  55201. if (min > max) {
  55202. temp = min;
  55203. min = max;
  55204. max = temp;
  55205. }
  55206. d = Math.max(min, d);
  55207. maxValue = Math.min(max, maxValue);
  55208. if (d > maxValue) {
  55209. return false;
  55210. }
  55211. }
  55212. if (Math.abs(this.direction.z) < 0.0000001) {
  55213. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55214. return false;
  55215. }
  55216. }
  55217. else {
  55218. inv = 1.0 / this.direction.z;
  55219. min = (minimum.z - this.origin.z) * inv;
  55220. max = (maximum.z - this.origin.z) * inv;
  55221. if (max === -Infinity) {
  55222. max = Infinity;
  55223. }
  55224. if (min > max) {
  55225. temp = min;
  55226. min = max;
  55227. max = temp;
  55228. }
  55229. d = Math.max(min, d);
  55230. maxValue = Math.min(max, maxValue);
  55231. if (d > maxValue) {
  55232. return false;
  55233. }
  55234. }
  55235. return true;
  55236. };
  55237. Ray.prototype.intersectsBox = function (box) {
  55238. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55239. };
  55240. Ray.prototype.intersectsSphere = function (sphere) {
  55241. var x = sphere.center.x - this.origin.x;
  55242. var y = sphere.center.y - this.origin.y;
  55243. var z = sphere.center.z - this.origin.z;
  55244. var pyth = (x * x) + (y * y) + (z * z);
  55245. var rr = sphere.radius * sphere.radius;
  55246. if (pyth <= rr) {
  55247. return true;
  55248. }
  55249. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55250. if (dot < 0.0) {
  55251. return false;
  55252. }
  55253. var temp = pyth - (dot * dot);
  55254. return temp <= rr;
  55255. };
  55256. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55257. if (!this._edge1) {
  55258. this._edge1 = BABYLON.Vector3.Zero();
  55259. this._edge2 = BABYLON.Vector3.Zero();
  55260. this._pvec = BABYLON.Vector3.Zero();
  55261. this._tvec = BABYLON.Vector3.Zero();
  55262. this._qvec = BABYLON.Vector3.Zero();
  55263. }
  55264. vertex1.subtractToRef(vertex0, this._edge1);
  55265. vertex2.subtractToRef(vertex0, this._edge2);
  55266. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55267. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55268. if (det === 0) {
  55269. return null;
  55270. }
  55271. var invdet = 1 / det;
  55272. this.origin.subtractToRef(vertex0, this._tvec);
  55273. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55274. if (bu < 0 || bu > 1.0) {
  55275. return null;
  55276. }
  55277. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55278. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55279. if (bv < 0 || bu + bv > 1.0) {
  55280. return null;
  55281. }
  55282. //check if the distance is longer than the predefined length.
  55283. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55284. if (distance > this.length) {
  55285. return null;
  55286. }
  55287. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55288. };
  55289. Ray.prototype.intersectsPlane = function (plane) {
  55290. var distance;
  55291. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55292. if (Math.abs(result1) < 9.99999997475243E-07) {
  55293. return null;
  55294. }
  55295. else {
  55296. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55297. distance = (-plane.d - result2) / result1;
  55298. if (distance < 0.0) {
  55299. if (distance < -9.99999997475243E-07) {
  55300. return null;
  55301. }
  55302. else {
  55303. return 0;
  55304. }
  55305. }
  55306. return distance;
  55307. }
  55308. };
  55309. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55310. var tm = BABYLON.Tmp.Matrix[0];
  55311. mesh.getWorldMatrix().invertToRef(tm);
  55312. if (this._tmpRay) {
  55313. Ray.TransformToRef(this, tm, this._tmpRay);
  55314. }
  55315. else {
  55316. this._tmpRay = Ray.Transform(this, tm);
  55317. }
  55318. return mesh.intersects(this._tmpRay, fastCheck);
  55319. };
  55320. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55321. if (results) {
  55322. results.length = 0;
  55323. }
  55324. else {
  55325. results = [];
  55326. }
  55327. for (var i = 0; i < meshes.length; i++) {
  55328. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55329. if (pickInfo.hit) {
  55330. results.push(pickInfo);
  55331. }
  55332. }
  55333. results.sort(this._comparePickingInfo);
  55334. return results;
  55335. };
  55336. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55337. if (pickingInfoA.distance < pickingInfoB.distance) {
  55338. return -1;
  55339. }
  55340. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55341. return 1;
  55342. }
  55343. else {
  55344. return 0;
  55345. }
  55346. };
  55347. /**
  55348. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55349. * @param sega the first point of the segment to test the intersection against
  55350. * @param segb the second point of the segment to test the intersection against
  55351. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55352. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55353. */
  55354. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55355. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55356. var u = segb.subtract(sega);
  55357. var v = rsegb.subtract(this.origin);
  55358. var w = sega.subtract(this.origin);
  55359. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55360. var b = BABYLON.Vector3.Dot(u, v);
  55361. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55362. var d = BABYLON.Vector3.Dot(u, w);
  55363. var e = BABYLON.Vector3.Dot(v, w);
  55364. var D = a * c - b * b; // always >= 0
  55365. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55366. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55367. // compute the line parameters of the two closest points
  55368. if (D < Ray.smallnum) { // the lines are almost parallel
  55369. sN = 0.0; // force using point P0 on segment S1
  55370. sD = 1.0; // to prevent possible division by 0.0 later
  55371. tN = e;
  55372. tD = c;
  55373. }
  55374. else { // get the closest points on the infinite lines
  55375. sN = (b * e - c * d);
  55376. tN = (a * e - b * d);
  55377. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55378. sN = 0.0;
  55379. tN = e;
  55380. tD = c;
  55381. }
  55382. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55383. sN = sD;
  55384. tN = e + b;
  55385. tD = c;
  55386. }
  55387. }
  55388. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55389. tN = 0.0;
  55390. // recompute sc for this edge
  55391. if (-d < 0.0) {
  55392. sN = 0.0;
  55393. }
  55394. else if (-d > a)
  55395. sN = sD;
  55396. else {
  55397. sN = -d;
  55398. sD = a;
  55399. }
  55400. }
  55401. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55402. tN = tD;
  55403. // recompute sc for this edge
  55404. if ((-d + b) < 0.0) {
  55405. sN = 0;
  55406. }
  55407. else if ((-d + b) > a) {
  55408. sN = sD;
  55409. }
  55410. else {
  55411. sN = (-d + b);
  55412. sD = a;
  55413. }
  55414. }
  55415. // finally do the division to get sc and tc
  55416. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55417. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55418. // get the difference of the two closest points
  55419. var qtc = v.multiplyByFloats(tc, tc, tc);
  55420. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55421. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55422. if (isIntersected) {
  55423. return qtc.length();
  55424. }
  55425. return -1;
  55426. };
  55427. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55428. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55429. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55430. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55431. this.direction.normalize();
  55432. return this;
  55433. };
  55434. // Statics
  55435. Ray.Zero = function () {
  55436. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55437. };
  55438. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55439. var result = Ray.Zero();
  55440. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55441. };
  55442. /**
  55443. * 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
  55444. * transformed to the given world matrix.
  55445. * @param origin The origin point
  55446. * @param end The end point
  55447. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55448. */
  55449. Ray.CreateNewFromTo = function (origin, end, world) {
  55450. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55451. var direction = end.subtract(origin);
  55452. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55453. direction.normalize();
  55454. return Ray.Transform(new Ray(origin, direction, length), world);
  55455. };
  55456. Ray.Transform = function (ray, matrix) {
  55457. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55458. Ray.TransformToRef(ray, matrix, result);
  55459. return result;
  55460. };
  55461. Ray.TransformToRef = function (ray, matrix, result) {
  55462. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55463. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55464. result.length = ray.length;
  55465. var dir = result.direction;
  55466. var len = dir.length();
  55467. if (!(len === 0 || len === 1)) {
  55468. var num = 1.0 / len;
  55469. dir.x *= num;
  55470. dir.y *= num;
  55471. dir.z *= num;
  55472. result.length *= len;
  55473. }
  55474. };
  55475. Ray.smallnum = 0.00000001;
  55476. Ray.rayl = 10e8;
  55477. return Ray;
  55478. }());
  55479. BABYLON.Ray = Ray;
  55480. })(BABYLON || (BABYLON = {}));
  55481. //# sourceMappingURL=babylon.ray.js.map
  55482. var BABYLON;
  55483. (function (BABYLON) {
  55484. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55485. if (boxMin.x > sphereCenter.x + sphereRadius)
  55486. return false;
  55487. if (sphereCenter.x - sphereRadius > boxMax.x)
  55488. return false;
  55489. if (boxMin.y > sphereCenter.y + sphereRadius)
  55490. return false;
  55491. if (sphereCenter.y - sphereRadius > boxMax.y)
  55492. return false;
  55493. if (boxMin.z > sphereCenter.z + sphereRadius)
  55494. return false;
  55495. if (sphereCenter.z - sphereRadius > boxMax.z)
  55496. return false;
  55497. return true;
  55498. };
  55499. var getLowestRoot = (function () {
  55500. var result = { root: 0, found: false };
  55501. return function (a, b, c, maxR) {
  55502. result.root = 0;
  55503. result.found = false;
  55504. var determinant = b * b - 4.0 * a * c;
  55505. if (determinant < 0)
  55506. return result;
  55507. var sqrtD = Math.sqrt(determinant);
  55508. var r1 = (-b - sqrtD) / (2.0 * a);
  55509. var r2 = (-b + sqrtD) / (2.0 * a);
  55510. if (r1 > r2) {
  55511. var temp = r2;
  55512. r2 = r1;
  55513. r1 = temp;
  55514. }
  55515. if (r1 > 0 && r1 < maxR) {
  55516. result.root = r1;
  55517. result.found = true;
  55518. return result;
  55519. }
  55520. if (r2 > 0 && r2 < maxR) {
  55521. result.root = r2;
  55522. result.found = true;
  55523. return result;
  55524. }
  55525. return result;
  55526. };
  55527. })();
  55528. var Collider = /** @class */ (function () {
  55529. function Collider() {
  55530. this._collisionPoint = BABYLON.Vector3.Zero();
  55531. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55532. this._tempVector = BABYLON.Vector3.Zero();
  55533. this._tempVector2 = BABYLON.Vector3.Zero();
  55534. this._tempVector3 = BABYLON.Vector3.Zero();
  55535. this._tempVector4 = BABYLON.Vector3.Zero();
  55536. this._edge = BABYLON.Vector3.Zero();
  55537. this._baseToVertex = BABYLON.Vector3.Zero();
  55538. this._destinationPoint = BABYLON.Vector3.Zero();
  55539. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55540. this._displacementVector = BABYLON.Vector3.Zero();
  55541. this._radius = BABYLON.Vector3.One();
  55542. this._retry = 0;
  55543. this._basePointWorld = BABYLON.Vector3.Zero();
  55544. this._velocityWorld = BABYLON.Vector3.Zero();
  55545. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55546. this._collisionMask = -1;
  55547. }
  55548. Object.defineProperty(Collider.prototype, "collisionMask", {
  55549. get: function () {
  55550. return this._collisionMask;
  55551. },
  55552. set: function (mask) {
  55553. this._collisionMask = !isNaN(mask) ? mask : -1;
  55554. },
  55555. enumerable: true,
  55556. configurable: true
  55557. });
  55558. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55559. /**
  55560. * Gets the plane normal used to compute the sliding response (in local space)
  55561. */
  55562. get: function () {
  55563. return this._slidePlaneNormal;
  55564. },
  55565. enumerable: true,
  55566. configurable: true
  55567. });
  55568. // Methods
  55569. Collider.prototype._initialize = function (source, dir, e) {
  55570. this._velocity = dir;
  55571. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55572. this._basePoint = source;
  55573. source.multiplyToRef(this._radius, this._basePointWorld);
  55574. dir.multiplyToRef(this._radius, this._velocityWorld);
  55575. this._velocityWorldLength = this._velocityWorld.length();
  55576. this._epsilon = e;
  55577. this.collisionFound = false;
  55578. };
  55579. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55580. pa.subtractToRef(point, this._tempVector);
  55581. pb.subtractToRef(point, this._tempVector2);
  55582. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55583. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55584. if (d < 0)
  55585. return false;
  55586. pc.subtractToRef(point, this._tempVector3);
  55587. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55588. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55589. if (d < 0)
  55590. return false;
  55591. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55592. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55593. return d >= 0;
  55594. };
  55595. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55596. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55597. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55598. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55599. return false;
  55600. }
  55601. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55602. return false;
  55603. return true;
  55604. };
  55605. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55606. var t0;
  55607. var embeddedInPlane = false;
  55608. //defensive programming, actually not needed.
  55609. if (!trianglePlaneArray) {
  55610. trianglePlaneArray = [];
  55611. }
  55612. if (!trianglePlaneArray[faceIndex]) {
  55613. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55614. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55615. }
  55616. var trianglePlane = trianglePlaneArray[faceIndex];
  55617. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55618. return;
  55619. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55620. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55621. if (normalDotVelocity == 0) {
  55622. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55623. return;
  55624. embeddedInPlane = true;
  55625. t0 = 0;
  55626. }
  55627. else {
  55628. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55629. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55630. if (t0 > t1) {
  55631. var temp = t1;
  55632. t1 = t0;
  55633. t0 = temp;
  55634. }
  55635. if (t0 > 1.0 || t1 < 0.0)
  55636. return;
  55637. if (t0 < 0)
  55638. t0 = 0;
  55639. if (t0 > 1.0)
  55640. t0 = 1.0;
  55641. }
  55642. this._collisionPoint.copyFromFloats(0, 0, 0);
  55643. var found = false;
  55644. var t = 1.0;
  55645. if (!embeddedInPlane) {
  55646. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55647. this._velocity.scaleToRef(t0, this._tempVector);
  55648. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55649. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55650. found = true;
  55651. t = t0;
  55652. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55653. }
  55654. }
  55655. if (!found) {
  55656. var velocitySquaredLength = this._velocity.lengthSquared();
  55657. var a = velocitySquaredLength;
  55658. this._basePoint.subtractToRef(p1, this._tempVector);
  55659. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55660. var c = this._tempVector.lengthSquared() - 1.0;
  55661. var lowestRoot = getLowestRoot(a, b, c, t);
  55662. if (lowestRoot.found) {
  55663. t = lowestRoot.root;
  55664. found = true;
  55665. this._collisionPoint.copyFrom(p1);
  55666. }
  55667. this._basePoint.subtractToRef(p2, this._tempVector);
  55668. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55669. c = this._tempVector.lengthSquared() - 1.0;
  55670. lowestRoot = getLowestRoot(a, b, c, t);
  55671. if (lowestRoot.found) {
  55672. t = lowestRoot.root;
  55673. found = true;
  55674. this._collisionPoint.copyFrom(p2);
  55675. }
  55676. this._basePoint.subtractToRef(p3, this._tempVector);
  55677. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55678. c = this._tempVector.lengthSquared() - 1.0;
  55679. lowestRoot = getLowestRoot(a, b, c, t);
  55680. if (lowestRoot.found) {
  55681. t = lowestRoot.root;
  55682. found = true;
  55683. this._collisionPoint.copyFrom(p3);
  55684. }
  55685. p2.subtractToRef(p1, this._edge);
  55686. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55687. var edgeSquaredLength = this._edge.lengthSquared();
  55688. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55689. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55690. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55691. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55692. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55693. lowestRoot = getLowestRoot(a, b, c, t);
  55694. if (lowestRoot.found) {
  55695. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55696. if (f >= 0.0 && f <= 1.0) {
  55697. t = lowestRoot.root;
  55698. found = true;
  55699. this._edge.scaleInPlace(f);
  55700. p1.addToRef(this._edge, this._collisionPoint);
  55701. }
  55702. }
  55703. p3.subtractToRef(p2, this._edge);
  55704. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55705. edgeSquaredLength = this._edge.lengthSquared();
  55706. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55707. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55708. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55709. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55710. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55711. lowestRoot = getLowestRoot(a, b, c, t);
  55712. if (lowestRoot.found) {
  55713. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55714. if (f >= 0.0 && f <= 1.0) {
  55715. t = lowestRoot.root;
  55716. found = true;
  55717. this._edge.scaleInPlace(f);
  55718. p2.addToRef(this._edge, this._collisionPoint);
  55719. }
  55720. }
  55721. p1.subtractToRef(p3, this._edge);
  55722. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55723. edgeSquaredLength = this._edge.lengthSquared();
  55724. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55725. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55726. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55727. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55728. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55729. lowestRoot = getLowestRoot(a, b, c, t);
  55730. if (lowestRoot.found) {
  55731. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55732. if (f >= 0.0 && f <= 1.0) {
  55733. t = lowestRoot.root;
  55734. found = true;
  55735. this._edge.scaleInPlace(f);
  55736. p3.addToRef(this._edge, this._collisionPoint);
  55737. }
  55738. }
  55739. }
  55740. if (found) {
  55741. var distToCollision = t * this._velocity.length();
  55742. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55743. if (!this.intersectionPoint) {
  55744. this.intersectionPoint = this._collisionPoint.clone();
  55745. }
  55746. else {
  55747. this.intersectionPoint.copyFrom(this._collisionPoint);
  55748. }
  55749. this._nearestDistance = distToCollision;
  55750. this.collisionFound = true;
  55751. }
  55752. }
  55753. };
  55754. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55755. for (var i = indexStart; i < indexEnd; i += 3) {
  55756. var p1 = pts[indices[i] - decal];
  55757. var p2 = pts[indices[i + 1] - decal];
  55758. var p3 = pts[indices[i + 2] - decal];
  55759. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55760. }
  55761. };
  55762. Collider.prototype._getResponse = function (pos, vel) {
  55763. pos.addToRef(vel, this._destinationPoint);
  55764. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55765. this._basePoint.addToRef(vel, pos);
  55766. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55767. this._slidePlaneNormal.normalize();
  55768. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55769. pos.addInPlace(this._displacementVector);
  55770. this.intersectionPoint.addInPlace(this._displacementVector);
  55771. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55772. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55773. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55774. };
  55775. return Collider;
  55776. }());
  55777. BABYLON.Collider = Collider;
  55778. })(BABYLON || (BABYLON = {}));
  55779. //# sourceMappingURL=babylon.collider.js.map
  55780. var BABYLON;
  55781. (function (BABYLON) {
  55782. //WebWorker code will be inserted to this variable.
  55783. BABYLON.CollisionWorker = "";
  55784. /** Defines supported task for worker process */
  55785. var WorkerTaskType;
  55786. (function (WorkerTaskType) {
  55787. /** Initialization */
  55788. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55789. /** Update of geometry */
  55790. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55791. /** Evaluate collision */
  55792. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55793. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55794. /** Defines kind of replies returned by worker */
  55795. var WorkerReplyType;
  55796. (function (WorkerReplyType) {
  55797. /** Success */
  55798. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55799. /** Unkown error */
  55800. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55801. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55802. var CollisionCoordinatorWorker = /** @class */ (function () {
  55803. function CollisionCoordinatorWorker() {
  55804. var _this = this;
  55805. this._scaledPosition = BABYLON.Vector3.Zero();
  55806. this._scaledVelocity = BABYLON.Vector3.Zero();
  55807. this.onMeshUpdated = function (transformNode) {
  55808. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55809. };
  55810. this.onGeometryUpdated = function (geometry) {
  55811. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55812. };
  55813. this._afterRender = function () {
  55814. if (!_this._init)
  55815. return;
  55816. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55817. return;
  55818. }
  55819. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55820. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55821. if (_this._runningUpdated > 4) {
  55822. return;
  55823. }
  55824. ++_this._runningUpdated;
  55825. var payload = {
  55826. updatedMeshes: _this._addUpdateMeshesList,
  55827. updatedGeometries: _this._addUpdateGeometriesList,
  55828. removedGeometries: _this._toRemoveGeometryArray,
  55829. removedMeshes: _this._toRemoveMeshesArray
  55830. };
  55831. var message = {
  55832. payload: payload,
  55833. taskType: WorkerTaskType.UPDATE
  55834. };
  55835. var serializable = [];
  55836. for (var id in payload.updatedGeometries) {
  55837. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55838. //prepare transferables
  55839. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55840. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55841. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55842. }
  55843. }
  55844. _this._worker.postMessage(message, serializable);
  55845. _this._addUpdateMeshesList = {};
  55846. _this._addUpdateGeometriesList = {};
  55847. _this._toRemoveGeometryArray = [];
  55848. _this._toRemoveMeshesArray = [];
  55849. };
  55850. this._onMessageFromWorker = function (e) {
  55851. var returnData = e.data;
  55852. if (returnData.error != WorkerReplyType.SUCCESS) {
  55853. //TODO what errors can be returned from the worker?
  55854. BABYLON.Tools.Warn("error returned from worker!");
  55855. return;
  55856. }
  55857. switch (returnData.taskType) {
  55858. case WorkerTaskType.INIT:
  55859. _this._init = true;
  55860. //Update the worked with ALL of the scene's current state
  55861. _this._scene.meshes.forEach(function (mesh) {
  55862. _this.onMeshAdded(mesh);
  55863. });
  55864. _this._scene.getGeometries().forEach(function (geometry) {
  55865. _this.onGeometryAdded(geometry);
  55866. });
  55867. break;
  55868. case WorkerTaskType.UPDATE:
  55869. _this._runningUpdated--;
  55870. break;
  55871. case WorkerTaskType.COLLIDE:
  55872. var returnPayload = returnData.payload;
  55873. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55874. return;
  55875. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55876. if (callback) {
  55877. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55878. if (mesh) {
  55879. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55880. }
  55881. }
  55882. //cleanup
  55883. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55884. break;
  55885. }
  55886. };
  55887. this._collisionsCallbackArray = [];
  55888. this._init = false;
  55889. this._runningUpdated = 0;
  55890. this._addUpdateMeshesList = {};
  55891. this._addUpdateGeometriesList = {};
  55892. this._toRemoveGeometryArray = [];
  55893. this._toRemoveMeshesArray = [];
  55894. }
  55895. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55896. if (!this._init)
  55897. return;
  55898. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55899. return;
  55900. position.divideToRef(collider._radius, this._scaledPosition);
  55901. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55902. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55903. var payload = {
  55904. collider: {
  55905. position: this._scaledPosition.asArray(),
  55906. velocity: this._scaledVelocity.asArray(),
  55907. radius: collider._radius.asArray()
  55908. },
  55909. collisionId: collisionIndex,
  55910. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55911. maximumRetry: maximumRetry
  55912. };
  55913. var message = {
  55914. payload: payload,
  55915. taskType: WorkerTaskType.COLLIDE
  55916. };
  55917. this._worker.postMessage(message);
  55918. };
  55919. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55920. this._scene = scene;
  55921. this._scene.registerAfterRender(this._afterRender);
  55922. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55923. this._worker = new Worker(workerUrl);
  55924. this._worker.onmessage = this._onMessageFromWorker;
  55925. var message = {
  55926. payload: {},
  55927. taskType: WorkerTaskType.INIT
  55928. };
  55929. this._worker.postMessage(message);
  55930. };
  55931. CollisionCoordinatorWorker.prototype.destroy = function () {
  55932. this._scene.unregisterAfterRender(this._afterRender);
  55933. this._worker.terminate();
  55934. };
  55935. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55936. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55937. this.onMeshUpdated(mesh);
  55938. };
  55939. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55940. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55941. };
  55942. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55943. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55944. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55945. this.onGeometryUpdated(geometry);
  55946. };
  55947. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55948. this._toRemoveGeometryArray.push(geometry.id);
  55949. };
  55950. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55951. var submeshes = [];
  55952. if (mesh.subMeshes) {
  55953. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55954. var boundingInfo = sm.getBoundingInfo();
  55955. return {
  55956. position: idx,
  55957. verticesStart: sm.verticesStart,
  55958. verticesCount: sm.verticesCount,
  55959. indexStart: sm.indexStart,
  55960. indexCount: sm.indexCount,
  55961. hasMaterial: !!sm.getMaterial(),
  55962. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55963. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55964. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55965. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55966. };
  55967. });
  55968. }
  55969. var geometryId = null;
  55970. if (mesh instanceof BABYLON.Mesh) {
  55971. var geometry = mesh.geometry;
  55972. geometryId = geometry ? geometry.id : null;
  55973. }
  55974. else if (mesh instanceof BABYLON.InstancedMesh) {
  55975. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55976. geometryId = geometry ? geometry.id : null;
  55977. }
  55978. var boundingInfo = mesh.getBoundingInfo();
  55979. return {
  55980. uniqueId: mesh.uniqueId,
  55981. id: mesh.id,
  55982. name: mesh.name,
  55983. geometryId: geometryId,
  55984. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55985. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55986. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55987. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55988. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55989. subMeshes: submeshes,
  55990. checkCollisions: mesh.checkCollisions
  55991. };
  55992. };
  55993. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55994. return {
  55995. id: geometry.id,
  55996. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55997. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55998. indices: new Uint32Array(geometry.getIndices() || []),
  55999. };
  56000. };
  56001. return CollisionCoordinatorWorker;
  56002. }());
  56003. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56004. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56005. function CollisionCoordinatorLegacy() {
  56006. this._scaledPosition = BABYLON.Vector3.Zero();
  56007. this._scaledVelocity = BABYLON.Vector3.Zero();
  56008. this._finalPosition = BABYLON.Vector3.Zero();
  56009. }
  56010. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56011. position.divideToRef(collider._radius, this._scaledPosition);
  56012. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56013. collider.collidedMesh = null;
  56014. collider._retry = 0;
  56015. collider._initialVelocity = this._scaledVelocity;
  56016. collider._initialPosition = this._scaledPosition;
  56017. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56018. this._finalPosition.multiplyInPlace(collider._radius);
  56019. //run the callback
  56020. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56021. };
  56022. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56023. this._scene = scene;
  56024. };
  56025. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56026. //Legacy need no destruction method.
  56027. };
  56028. //No update in legacy mode
  56029. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56030. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56031. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56032. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56033. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56034. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56035. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56036. if (excludedMesh === void 0) { excludedMesh = null; }
  56037. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56038. if (collider._retry >= maximumRetry) {
  56039. finalPosition.copyFrom(position);
  56040. return;
  56041. }
  56042. // Check if this is a mesh else camera or -1
  56043. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56044. collider._initialize(position, velocity, closeDistance);
  56045. // Check all meshes
  56046. for (var index = 0; index < this._scene.meshes.length; index++) {
  56047. var mesh = this._scene.meshes[index];
  56048. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56049. mesh._checkCollision(collider);
  56050. }
  56051. }
  56052. if (!collider.collisionFound) {
  56053. position.addToRef(velocity, finalPosition);
  56054. return;
  56055. }
  56056. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56057. collider._getResponse(position, velocity);
  56058. }
  56059. if (velocity.length() <= closeDistance) {
  56060. finalPosition.copyFrom(position);
  56061. return;
  56062. }
  56063. collider._retry++;
  56064. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56065. };
  56066. return CollisionCoordinatorLegacy;
  56067. }());
  56068. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56069. })(BABYLON || (BABYLON = {}));
  56070. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56071. var BABYLON;
  56072. (function (BABYLON) {
  56073. /**
  56074. * A particle represents one of the element emitted by a particle system.
  56075. * This is mainly define by its coordinates, direction, velocity and age.
  56076. */
  56077. var Particle = /** @class */ (function () {
  56078. /**
  56079. * Creates a new instance Particle
  56080. * @param particleSystem the particle system the particle belongs to
  56081. */
  56082. function Particle(
  56083. /**
  56084. * particleSystem the particle system the particle belongs to.
  56085. */
  56086. particleSystem) {
  56087. this.particleSystem = particleSystem;
  56088. /**
  56089. * The world position of the particle in the scene.
  56090. */
  56091. this.position = BABYLON.Vector3.Zero();
  56092. /**
  56093. * The world direction of the particle in the scene.
  56094. */
  56095. this.direction = BABYLON.Vector3.Zero();
  56096. /**
  56097. * The color of the particle.
  56098. */
  56099. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56100. /**
  56101. * The color change of the particle per step.
  56102. */
  56103. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56104. /**
  56105. * Defines how long will the life of the particle be.
  56106. */
  56107. this.lifeTime = 1.0;
  56108. /**
  56109. * The current age of the particle.
  56110. */
  56111. this.age = 0;
  56112. /**
  56113. * The current size of the particle.
  56114. */
  56115. this.size = 0;
  56116. /**
  56117. * The current angle of the particle.
  56118. */
  56119. this.angle = 0;
  56120. /**
  56121. * Defines how fast is the angle changing.
  56122. */
  56123. this.angularSpeed = 0;
  56124. /**
  56125. * Defines the cell index used by the particle to be rendered from a sprite.
  56126. */
  56127. this.cellIndex = 0;
  56128. this._currentFrameCounter = 0;
  56129. if (!this.particleSystem.isAnimationSheetEnabled) {
  56130. return;
  56131. }
  56132. this.updateCellInfoFromSystem();
  56133. }
  56134. Particle.prototype.updateCellInfoFromSystem = function () {
  56135. this.cellIndex = this.particleSystem.startSpriteCellID;
  56136. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  56137. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  56138. }
  56139. else {
  56140. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56141. }
  56142. };
  56143. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56144. // (ageOffset / scaledUpdateSpeed) / available cells
  56145. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56146. this._currentFrameCounter += scaledUpdateSpeed;
  56147. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56148. this._currentFrameCounter = 0;
  56149. this.cellIndex++;
  56150. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56151. this.cellIndex = this.particleSystem.endSpriteCellID;
  56152. }
  56153. }
  56154. };
  56155. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56156. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56157. this.cellIndex++;
  56158. this._currentFrameCounter = 0;
  56159. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56160. if (this.particleSystem.spriteCellLoop) {
  56161. this.cellIndex = this.particleSystem.startSpriteCellID;
  56162. }
  56163. else {
  56164. this.cellIndex = this.particleSystem.endSpriteCellID;
  56165. }
  56166. }
  56167. }
  56168. else {
  56169. this._currentFrameCounter++;
  56170. }
  56171. };
  56172. /**
  56173. * Copy the properties of particle to another one.
  56174. * @param other the particle to copy the information to.
  56175. */
  56176. Particle.prototype.copyTo = function (other) {
  56177. other.position.copyFrom(this.position);
  56178. other.direction.copyFrom(this.direction);
  56179. other.color.copyFrom(this.color);
  56180. other.colorStep.copyFrom(this.colorStep);
  56181. other.lifeTime = this.lifeTime;
  56182. other.age = this.age;
  56183. other.size = this.size;
  56184. other.angle = this.angle;
  56185. other.angularSpeed = this.angularSpeed;
  56186. other.particleSystem = this.particleSystem;
  56187. other.cellIndex = this.cellIndex;
  56188. };
  56189. return Particle;
  56190. }());
  56191. BABYLON.Particle = Particle;
  56192. })(BABYLON || (BABYLON = {}));
  56193. //# sourceMappingURL=babylon.particle.js.map
  56194. var BABYLON;
  56195. (function (BABYLON) {
  56196. /**
  56197. * This represents a particle system in Babylon.
  56198. * 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.
  56199. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56200. * @example https://doc.babylonjs.com/babylon101/particles
  56201. */
  56202. var ParticleSystem = /** @class */ (function () {
  56203. /**
  56204. * Instantiates a particle system.
  56205. * 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.
  56206. * @param name The name of the particle system
  56207. * @param capacity The max number of particles alive at the same time
  56208. * @param scene The scene the particle system belongs to
  56209. * @param customEffect a custom effect used to change the way particles are rendered by default
  56210. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56211. * @param epsilon Offset used to render the particles
  56212. */
  56213. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56214. if (customEffect === void 0) { customEffect = null; }
  56215. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56216. if (epsilon === void 0) { epsilon = 0.01; }
  56217. var _this = this;
  56218. /**
  56219. * List of animations used by the particle system.
  56220. */
  56221. this.animations = [];
  56222. /**
  56223. * The rendering group used by the Particle system to chose when to render.
  56224. */
  56225. this.renderingGroupId = 0;
  56226. /**
  56227. * The emitter represents the Mesh or position we are attaching the particle system to.
  56228. */
  56229. this.emitter = null;
  56230. /**
  56231. * The maximum number of particles to emit per frame
  56232. */
  56233. this.emitRate = 10;
  56234. /**
  56235. * If you want to launch only a few particles at once, that can be done, as well.
  56236. */
  56237. this.manualEmitCount = -1;
  56238. /**
  56239. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56240. */
  56241. this.updateSpeed = 0.01;
  56242. /**
  56243. * The amount of time the particle system is running (depends of the overall update speed).
  56244. */
  56245. this.targetStopDuration = 0;
  56246. /**
  56247. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56248. */
  56249. this.disposeOnStop = false;
  56250. /**
  56251. * Minimum power of emitting particles.
  56252. */
  56253. this.minEmitPower = 1;
  56254. /**
  56255. * Maximum power of emitting particles.
  56256. */
  56257. this.maxEmitPower = 1;
  56258. /**
  56259. * Minimum life time of emitting particles.
  56260. */
  56261. this.minLifeTime = 1;
  56262. /**
  56263. * Maximum life time of emitting particles.
  56264. */
  56265. this.maxLifeTime = 1;
  56266. /**
  56267. * Minimum Size of emitting particles.
  56268. */
  56269. this.minSize = 1;
  56270. /**
  56271. * Maximum Size of emitting particles.
  56272. */
  56273. this.maxSize = 1;
  56274. /**
  56275. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56276. */
  56277. this.minAngularSpeed = 0;
  56278. /**
  56279. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56280. */
  56281. this.maxAngularSpeed = 0;
  56282. /**
  56283. * The layer mask we are rendering the particles through.
  56284. */
  56285. this.layerMask = 0x0FFFFFFF;
  56286. /**
  56287. * This can help using your own shader to render the particle system.
  56288. * The according effect will be created
  56289. */
  56290. this.customShader = null;
  56291. /**
  56292. * By default particle system starts as soon as they are created. This prevents the
  56293. * automatic start to happen and let you decide when to start emitting particles.
  56294. */
  56295. this.preventAutoStart = false;
  56296. /**
  56297. * Callback triggered when the particle animation is ending.
  56298. */
  56299. this.onAnimationEnd = null;
  56300. /**
  56301. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56302. */
  56303. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56304. /**
  56305. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56306. * to override the particles.
  56307. */
  56308. this.forceDepthWrite = false;
  56309. /**
  56310. * You can use gravity if you want to give an orientation to your particles.
  56311. */
  56312. this.gravity = BABYLON.Vector3.Zero();
  56313. /**
  56314. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56315. */
  56316. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56317. /**
  56318. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56319. */
  56320. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56321. /**
  56322. * Color the particle will have at the end of its lifetime.
  56323. */
  56324. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56325. /**
  56326. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56327. */
  56328. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56329. /**
  56330. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56331. */
  56332. this.spriteCellLoop = true;
  56333. /**
  56334. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56335. */
  56336. this.spriteCellChangeSpeed = 0;
  56337. /**
  56338. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56339. */
  56340. this.startSpriteCellID = 0;
  56341. /**
  56342. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56343. */
  56344. this.endSpriteCellID = 0;
  56345. /**
  56346. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56347. */
  56348. this.spriteCellWidth = 0;
  56349. /**
  56350. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56351. */
  56352. this.spriteCellHeight = 0;
  56353. /**
  56354. * An event triggered when the system is disposed.
  56355. */
  56356. this.onDisposeObservable = new BABYLON.Observable();
  56357. this._particles = new Array();
  56358. this._stockParticles = new Array();
  56359. this._newPartsExcess = 0;
  56360. this._vertexBuffers = {};
  56361. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56362. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56363. this._scaledDirection = BABYLON.Vector3.Zero();
  56364. this._scaledGravity = BABYLON.Vector3.Zero();
  56365. this._currentRenderId = -1;
  56366. this._started = false;
  56367. this._stopped = false;
  56368. this._actualFrame = 0;
  56369. this._vertexBufferSize = 11;
  56370. // start of sub system methods
  56371. /**
  56372. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56373. * Its lifetime will start back at 0.
  56374. */
  56375. this.recycleParticle = function (particle) {
  56376. var lastParticle = _this._particles.pop();
  56377. if (lastParticle !== particle) {
  56378. lastParticle.copyTo(particle);
  56379. }
  56380. _this._stockParticles.push(lastParticle);
  56381. };
  56382. this._createParticle = function () {
  56383. var particle;
  56384. if (_this._stockParticles.length !== 0) {
  56385. particle = _this._stockParticles.pop();
  56386. particle.age = 0;
  56387. particle.cellIndex = _this.startSpriteCellID;
  56388. }
  56389. else {
  56390. particle = new BABYLON.Particle(_this);
  56391. }
  56392. return particle;
  56393. };
  56394. this._emitFromParticle = function (particle) {
  56395. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56396. return;
  56397. }
  56398. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56399. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56400. subSystem._rootParticleSystem = _this;
  56401. _this.activeSubSystems.push(subSystem);
  56402. subSystem.start();
  56403. };
  56404. this._appendParticleVertexes = null;
  56405. this.id = name;
  56406. this.name = name;
  56407. this._capacity = capacity;
  56408. this._epsilon = epsilon;
  56409. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56410. if (isAnimationSheetEnabled) {
  56411. this._vertexBufferSize = 12;
  56412. }
  56413. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56414. this._customEffect = customEffect;
  56415. scene.particleSystems.push(this);
  56416. this._createIndexBuffer();
  56417. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56418. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56419. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56420. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56421. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56422. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56423. if (this._isAnimationSheetEnabled) {
  56424. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56425. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56426. }
  56427. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56428. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56429. this._vertexBuffers["options"] = options;
  56430. // Default emitter type
  56431. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56432. this.updateFunction = function (particles) {
  56433. for (var index = 0; index < particles.length; index++) {
  56434. var particle = particles[index];
  56435. particle.age += _this._scaledUpdateSpeed;
  56436. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56437. _this._emitFromParticle(particle);
  56438. _this.recycleParticle(particle);
  56439. index--;
  56440. continue;
  56441. }
  56442. else {
  56443. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56444. particle.color.addInPlace(_this._scaledColorStep);
  56445. if (particle.color.a < 0)
  56446. particle.color.a = 0;
  56447. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56448. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56449. particle.position.addInPlace(_this._scaledDirection);
  56450. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56451. particle.direction.addInPlace(_this._scaledGravity);
  56452. if (_this._isAnimationSheetEnabled) {
  56453. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56454. }
  56455. }
  56456. }
  56457. };
  56458. }
  56459. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56460. /**
  56461. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56462. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56463. */
  56464. get: function () {
  56465. if (this.particleEmitterType.direction1) {
  56466. return this.particleEmitterType.direction1;
  56467. }
  56468. return BABYLON.Vector3.Zero();
  56469. },
  56470. set: function (value) {
  56471. if (this.particleEmitterType.direction1) {
  56472. this.particleEmitterType.direction1 = value;
  56473. }
  56474. },
  56475. enumerable: true,
  56476. configurable: true
  56477. });
  56478. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56479. /**
  56480. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56481. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56482. */
  56483. get: function () {
  56484. if (this.particleEmitterType.direction2) {
  56485. return this.particleEmitterType.direction2;
  56486. }
  56487. return BABYLON.Vector3.Zero();
  56488. },
  56489. set: function (value) {
  56490. if (this.particleEmitterType.direction2) {
  56491. this.particleEmitterType.direction2 = value;
  56492. }
  56493. },
  56494. enumerable: true,
  56495. configurable: true
  56496. });
  56497. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56498. /**
  56499. * 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.
  56500. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56501. */
  56502. get: function () {
  56503. if (this.particleEmitterType.minEmitBox) {
  56504. return this.particleEmitterType.minEmitBox;
  56505. }
  56506. return BABYLON.Vector3.Zero();
  56507. },
  56508. set: function (value) {
  56509. if (this.particleEmitterType.minEmitBox) {
  56510. this.particleEmitterType.minEmitBox = value;
  56511. }
  56512. },
  56513. enumerable: true,
  56514. configurable: true
  56515. });
  56516. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56517. /**
  56518. * 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.
  56519. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56520. */
  56521. get: function () {
  56522. if (this.particleEmitterType.maxEmitBox) {
  56523. return this.particleEmitterType.maxEmitBox;
  56524. }
  56525. return BABYLON.Vector3.Zero();
  56526. },
  56527. set: function (value) {
  56528. if (this.particleEmitterType.maxEmitBox) {
  56529. this.particleEmitterType.maxEmitBox = value;
  56530. }
  56531. },
  56532. enumerable: true,
  56533. configurable: true
  56534. });
  56535. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56536. /**
  56537. * Sets a callback that will be triggered when the system is disposed.
  56538. */
  56539. set: function (callback) {
  56540. if (this._onDisposeObserver) {
  56541. this.onDisposeObservable.remove(this._onDisposeObserver);
  56542. }
  56543. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56544. },
  56545. enumerable: true,
  56546. configurable: true
  56547. });
  56548. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56549. /**
  56550. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56551. */
  56552. get: function () {
  56553. return this._isAnimationSheetEnabled;
  56554. },
  56555. enumerable: true,
  56556. configurable: true
  56557. });
  56558. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56559. //end of Sub-emitter
  56560. /**
  56561. * Gets the current list of active particles
  56562. */
  56563. get: function () {
  56564. return this._particles;
  56565. },
  56566. enumerable: true,
  56567. configurable: true
  56568. });
  56569. /**
  56570. * Returns the string "ParticleSystem"
  56571. * @returns a string containing the class name
  56572. */
  56573. ParticleSystem.prototype.getClassName = function () {
  56574. return "ParticleSystem";
  56575. };
  56576. ParticleSystem.prototype._createIndexBuffer = function () {
  56577. var indices = [];
  56578. var index = 0;
  56579. for (var count = 0; count < this._capacity; count++) {
  56580. indices.push(index);
  56581. indices.push(index + 1);
  56582. indices.push(index + 2);
  56583. indices.push(index);
  56584. indices.push(index + 2);
  56585. indices.push(index + 3);
  56586. index += 4;
  56587. }
  56588. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56589. };
  56590. /**
  56591. * Gets the maximum number of particles active at the same time.
  56592. * @returns The max number of active particles.
  56593. */
  56594. ParticleSystem.prototype.getCapacity = function () {
  56595. return this._capacity;
  56596. };
  56597. /**
  56598. * Gets Wether there are still active particles in the system.
  56599. * @returns True if it is alive, otherwise false.
  56600. */
  56601. ParticleSystem.prototype.isAlive = function () {
  56602. return this._alive;
  56603. };
  56604. /**
  56605. * Gets Wether the system has been started.
  56606. * @returns True if it has been started, otherwise false.
  56607. */
  56608. ParticleSystem.prototype.isStarted = function () {
  56609. return this._started;
  56610. };
  56611. /**
  56612. * Starts the particle system and begins to emit.
  56613. */
  56614. ParticleSystem.prototype.start = function () {
  56615. this._started = true;
  56616. this._stopped = false;
  56617. this._actualFrame = 0;
  56618. if (this.subEmitters && this.subEmitters.length != 0) {
  56619. this.activeSubSystems = new Array();
  56620. }
  56621. };
  56622. /**
  56623. * Stops the particle system.
  56624. * @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.
  56625. */
  56626. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56627. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56628. this._stopped = true;
  56629. if (stopSubEmitters) {
  56630. this._stopSubEmitters();
  56631. }
  56632. };
  56633. // animation sheet
  56634. /**
  56635. * Remove all active particles
  56636. */
  56637. ParticleSystem.prototype.reset = function () {
  56638. this._stockParticles = [];
  56639. this._particles = [];
  56640. };
  56641. /**
  56642. * @hidden (for internal use only)
  56643. */
  56644. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56645. var offset = index * this._vertexBufferSize;
  56646. this._vertexData[offset] = particle.position.x;
  56647. this._vertexData[offset + 1] = particle.position.y;
  56648. this._vertexData[offset + 2] = particle.position.z;
  56649. this._vertexData[offset + 3] = particle.color.r;
  56650. this._vertexData[offset + 4] = particle.color.g;
  56651. this._vertexData[offset + 5] = particle.color.b;
  56652. this._vertexData[offset + 6] = particle.color.a;
  56653. this._vertexData[offset + 7] = particle.angle;
  56654. this._vertexData[offset + 8] = particle.size;
  56655. this._vertexData[offset + 9] = offsetX;
  56656. this._vertexData[offset + 10] = offsetY;
  56657. };
  56658. /**
  56659. * @hidden (for internal use only)
  56660. */
  56661. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56662. if (offsetX === 0)
  56663. offsetX = this._epsilon;
  56664. else if (offsetX === 1)
  56665. offsetX = 1 - this._epsilon;
  56666. if (offsetY === 0)
  56667. offsetY = this._epsilon;
  56668. else if (offsetY === 1)
  56669. offsetY = 1 - this._epsilon;
  56670. var offset = index * this._vertexBufferSize;
  56671. this._vertexData[offset] = particle.position.x;
  56672. this._vertexData[offset + 1] = particle.position.y;
  56673. this._vertexData[offset + 2] = particle.position.z;
  56674. this._vertexData[offset + 3] = particle.color.r;
  56675. this._vertexData[offset + 4] = particle.color.g;
  56676. this._vertexData[offset + 5] = particle.color.b;
  56677. this._vertexData[offset + 6] = particle.color.a;
  56678. this._vertexData[offset + 7] = particle.angle;
  56679. this._vertexData[offset + 8] = particle.size;
  56680. this._vertexData[offset + 9] = offsetX;
  56681. this._vertexData[offset + 10] = offsetY;
  56682. this._vertexData[offset + 11] = particle.cellIndex;
  56683. };
  56684. ParticleSystem.prototype._stopSubEmitters = function () {
  56685. if (!this.activeSubSystems) {
  56686. return;
  56687. }
  56688. this.activeSubSystems.forEach(function (subSystem) {
  56689. subSystem.stop(true);
  56690. });
  56691. this.activeSubSystems = new Array();
  56692. };
  56693. ParticleSystem.prototype._removeFromRoot = function () {
  56694. if (!this._rootParticleSystem) {
  56695. return;
  56696. }
  56697. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56698. if (index !== -1) {
  56699. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56700. }
  56701. };
  56702. // end of sub system methods
  56703. ParticleSystem.prototype._update = function (newParticles) {
  56704. // Update current
  56705. this._alive = this._particles.length > 0;
  56706. this.updateFunction(this._particles);
  56707. // Add new ones
  56708. var worldMatrix;
  56709. if (this.emitter.position) {
  56710. var emitterMesh = this.emitter;
  56711. worldMatrix = emitterMesh.getWorldMatrix();
  56712. }
  56713. else {
  56714. var emitterPosition = this.emitter;
  56715. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56716. }
  56717. var particle;
  56718. for (var index = 0; index < newParticles; index++) {
  56719. if (this._particles.length === this._capacity) {
  56720. break;
  56721. }
  56722. particle = this._createParticle();
  56723. this._particles.push(particle);
  56724. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56725. if (this.startPositionFunction) {
  56726. this.startPositionFunction(worldMatrix, particle.position, particle);
  56727. }
  56728. else {
  56729. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56730. }
  56731. if (this.startDirectionFunction) {
  56732. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56733. }
  56734. else {
  56735. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56736. }
  56737. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56738. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56739. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56740. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56741. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56742. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56743. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56744. }
  56745. };
  56746. ParticleSystem.prototype._getEffect = function () {
  56747. if (this._customEffect) {
  56748. return this._customEffect;
  56749. }
  56750. ;
  56751. var defines = [];
  56752. if (this._scene.clipPlane) {
  56753. defines.push("#define CLIPPLANE");
  56754. }
  56755. if (this._isAnimationSheetEnabled) {
  56756. defines.push("#define ANIMATESHEET");
  56757. }
  56758. // Effect
  56759. var join = defines.join("\n");
  56760. if (this._cachedDefines !== join) {
  56761. this._cachedDefines = join;
  56762. var attributesNamesOrOptions;
  56763. var effectCreationOption;
  56764. if (this._isAnimationSheetEnabled) {
  56765. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56766. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56767. }
  56768. else {
  56769. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56770. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56771. }
  56772. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56773. }
  56774. return this._effect;
  56775. };
  56776. /**
  56777. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56778. */
  56779. ParticleSystem.prototype.animate = function () {
  56780. if (!this._started)
  56781. return;
  56782. var effect = this._getEffect();
  56783. // Check
  56784. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56785. return;
  56786. if (this._currentRenderId === this._scene.getRenderId()) {
  56787. return;
  56788. }
  56789. this._currentRenderId = this._scene.getRenderId();
  56790. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56791. // determine the number of particles we need to create
  56792. var newParticles;
  56793. if (this.manualEmitCount > -1) {
  56794. newParticles = this.manualEmitCount;
  56795. this._newPartsExcess = 0;
  56796. this.manualEmitCount = 0;
  56797. }
  56798. else {
  56799. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56800. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56801. }
  56802. if (this._newPartsExcess > 1.0) {
  56803. newParticles += this._newPartsExcess >> 0;
  56804. this._newPartsExcess -= this._newPartsExcess >> 0;
  56805. }
  56806. this._alive = false;
  56807. if (!this._stopped) {
  56808. this._actualFrame += this._scaledUpdateSpeed;
  56809. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56810. this.stop();
  56811. }
  56812. else {
  56813. newParticles = 0;
  56814. }
  56815. this._update(newParticles);
  56816. // Stopped?
  56817. if (this._stopped) {
  56818. if (!this._alive) {
  56819. this._started = false;
  56820. if (this.onAnimationEnd) {
  56821. this.onAnimationEnd();
  56822. }
  56823. if (this.disposeOnStop) {
  56824. this._scene._toBeDisposed.push(this);
  56825. }
  56826. }
  56827. }
  56828. // Animation sheet
  56829. if (this._isAnimationSheetEnabled) {
  56830. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56831. }
  56832. else {
  56833. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56834. }
  56835. // Update VBO
  56836. var offset = 0;
  56837. for (var index = 0; index < this._particles.length; index++) {
  56838. var particle = this._particles[index];
  56839. this._appendParticleVertexes(offset, particle);
  56840. offset += 4;
  56841. }
  56842. if (this._vertexBuffer) {
  56843. this._vertexBuffer.update(this._vertexData);
  56844. }
  56845. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56846. this.stop();
  56847. }
  56848. };
  56849. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56850. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56851. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56852. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56853. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56854. };
  56855. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56856. this._appendParticleVertex(offset++, particle, 0, 0);
  56857. this._appendParticleVertex(offset++, particle, 1, 0);
  56858. this._appendParticleVertex(offset++, particle, 1, 1);
  56859. this._appendParticleVertex(offset++, particle, 0, 1);
  56860. };
  56861. /**
  56862. * Rebuilds the particle system.
  56863. */
  56864. ParticleSystem.prototype.rebuild = function () {
  56865. this._createIndexBuffer();
  56866. if (this._vertexBuffer) {
  56867. this._vertexBuffer._rebuild();
  56868. }
  56869. };
  56870. /**
  56871. * Is this system ready to be used/rendered
  56872. * @return true if the system is ready
  56873. */
  56874. ParticleSystem.prototype.isReady = function () {
  56875. var effect = this._getEffect();
  56876. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56877. return false;
  56878. }
  56879. return true;
  56880. };
  56881. /**
  56882. * Renders the particle system in its current state.
  56883. * @returns the current number of particles
  56884. */
  56885. ParticleSystem.prototype.render = function () {
  56886. var effect = this._getEffect();
  56887. // Check
  56888. if (!this.isReady() || !this._particles.length) {
  56889. return 0;
  56890. }
  56891. var engine = this._scene.getEngine();
  56892. // Render
  56893. engine.enableEffect(effect);
  56894. engine.setState(false);
  56895. var viewMatrix = this._scene.getViewMatrix();
  56896. effect.setTexture("diffuseSampler", this.particleTexture);
  56897. effect.setMatrix("view", viewMatrix);
  56898. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56899. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56900. var baseSize = this.particleTexture.getBaseSize();
  56901. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56902. }
  56903. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56904. if (this._scene.clipPlane) {
  56905. var clipPlane = this._scene.clipPlane;
  56906. var invView = viewMatrix.clone();
  56907. invView.invert();
  56908. effect.setMatrix("invView", invView);
  56909. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56910. }
  56911. // VBOs
  56912. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56913. // Draw order
  56914. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56915. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56916. }
  56917. else {
  56918. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56919. }
  56920. if (this.forceDepthWrite) {
  56921. engine.setDepthWrite(true);
  56922. }
  56923. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56924. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56925. return this._particles.length;
  56926. };
  56927. /**
  56928. * Disposes the particle system and free the associated resources
  56929. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56930. */
  56931. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56932. if (disposeTexture === void 0) { disposeTexture = true; }
  56933. if (this._vertexBuffer) {
  56934. this._vertexBuffer.dispose();
  56935. this._vertexBuffer = null;
  56936. }
  56937. if (this._indexBuffer) {
  56938. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56939. this._indexBuffer = null;
  56940. }
  56941. if (disposeTexture && this.particleTexture) {
  56942. this.particleTexture.dispose();
  56943. this.particleTexture = null;
  56944. }
  56945. this._removeFromRoot();
  56946. // Remove from scene
  56947. var index = this._scene.particleSystems.indexOf(this);
  56948. if (index > -1) {
  56949. this._scene.particleSystems.splice(index, 1);
  56950. }
  56951. // Callback
  56952. this.onDisposeObservable.notifyObservers(this);
  56953. this.onDisposeObservable.clear();
  56954. };
  56955. /**
  56956. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56957. * @param radius The radius of the sphere to emit from
  56958. * @returns the emitter
  56959. */
  56960. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56961. if (radius === void 0) { radius = 1; }
  56962. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56963. this.particleEmitterType = particleEmitter;
  56964. return particleEmitter;
  56965. };
  56966. /**
  56967. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56968. * @param radius The radius of the sphere to emit from
  56969. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56970. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56971. * @returns the emitter
  56972. */
  56973. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56974. if (radius === void 0) { radius = 1; }
  56975. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56976. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56977. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56978. this.particleEmitterType = particleEmitter;
  56979. return particleEmitter;
  56980. };
  56981. /**
  56982. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56983. * @param radius The radius of the cone to emit from
  56984. * @param angle The base angle of the cone
  56985. * @returns the emitter
  56986. */
  56987. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56988. if (radius === void 0) { radius = 1; }
  56989. if (angle === void 0) { angle = Math.PI / 4; }
  56990. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56991. this.particleEmitterType = particleEmitter;
  56992. return particleEmitter;
  56993. };
  56994. // 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.
  56995. /**
  56996. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56997. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56998. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56999. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57000. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57001. * @returns the emitter
  57002. */
  57003. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57004. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57005. this.particleEmitterType = particleEmitter;
  57006. this.direction1 = direction1;
  57007. this.direction2 = direction2;
  57008. this.minEmitBox = minEmitBox;
  57009. this.maxEmitBox = maxEmitBox;
  57010. return particleEmitter;
  57011. };
  57012. // Clone
  57013. /**
  57014. * Clones the particle system.
  57015. * @param name The name of the cloned object
  57016. * @param newEmitter The new emitter to use
  57017. * @returns the cloned particle system
  57018. */
  57019. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57020. var custom = null;
  57021. var program = null;
  57022. if (this.customShader != null) {
  57023. program = this.customShader;
  57024. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57025. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57026. }
  57027. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57028. result.customShader = program;
  57029. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57030. if (newEmitter === undefined) {
  57031. newEmitter = this.emitter;
  57032. }
  57033. result.emitter = newEmitter;
  57034. if (this.particleTexture) {
  57035. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57036. }
  57037. if (!this.preventAutoStart) {
  57038. result.start();
  57039. }
  57040. return result;
  57041. };
  57042. /**
  57043. * Serializes the particle system to a JSON object.
  57044. * @returns the JSON object
  57045. */
  57046. ParticleSystem.prototype.serialize = function () {
  57047. var serializationObject = {};
  57048. serializationObject.name = this.name;
  57049. serializationObject.id = this.id;
  57050. // Emitter
  57051. if (this.emitter.position) {
  57052. var emitterMesh = this.emitter;
  57053. serializationObject.emitterId = emitterMesh.id;
  57054. }
  57055. else {
  57056. var emitterPosition = this.emitter;
  57057. serializationObject.emitter = emitterPosition.asArray();
  57058. }
  57059. serializationObject.capacity = this.getCapacity();
  57060. if (this.particleTexture) {
  57061. serializationObject.textureName = this.particleTexture.name;
  57062. }
  57063. // Animations
  57064. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57065. // Particle system
  57066. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57067. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57068. serializationObject.minSize = this.minSize;
  57069. serializationObject.maxSize = this.maxSize;
  57070. serializationObject.minEmitPower = this.minEmitPower;
  57071. serializationObject.maxEmitPower = this.maxEmitPower;
  57072. serializationObject.minLifeTime = this.minLifeTime;
  57073. serializationObject.maxLifeTime = this.maxLifeTime;
  57074. serializationObject.emitRate = this.emitRate;
  57075. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57076. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57077. serializationObject.gravity = this.gravity.asArray();
  57078. serializationObject.direction1 = this.direction1.asArray();
  57079. serializationObject.direction2 = this.direction2.asArray();
  57080. serializationObject.color1 = this.color1.asArray();
  57081. serializationObject.color2 = this.color2.asArray();
  57082. serializationObject.colorDead = this.colorDead.asArray();
  57083. serializationObject.updateSpeed = this.updateSpeed;
  57084. serializationObject.targetStopDuration = this.targetStopDuration;
  57085. serializationObject.textureMask = this.textureMask.asArray();
  57086. serializationObject.blendMode = this.blendMode;
  57087. serializationObject.customShader = this.customShader;
  57088. serializationObject.preventAutoStart = this.preventAutoStart;
  57089. serializationObject.startSpriteCellID = this.startSpriteCellID;
  57090. serializationObject.endSpriteCellID = this.endSpriteCellID;
  57091. serializationObject.spriteCellLoop = this.spriteCellLoop;
  57092. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  57093. serializationObject.spriteCellWidth = this.spriteCellWidth;
  57094. serializationObject.spriteCellHeight = this.spriteCellHeight;
  57095. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57096. // Emitter
  57097. if (this.particleEmitterType) {
  57098. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57099. }
  57100. return serializationObject;
  57101. };
  57102. /**
  57103. * Parses a JSON object to create a particle system.
  57104. * @param parsedParticleSystem The JSON object to parse
  57105. * @param scene The scene to create the particle system in
  57106. * @param rootUrl The root url to use to load external dependencies like texture
  57107. * @returns the Parsed particle system
  57108. */
  57109. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57110. var name = parsedParticleSystem.name;
  57111. var custom = null;
  57112. var program = null;
  57113. if (parsedParticleSystem.customShader) {
  57114. program = parsedParticleSystem.customShader;
  57115. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57116. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57117. }
  57118. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57119. particleSystem.customShader = program;
  57120. if (parsedParticleSystem.id) {
  57121. particleSystem.id = parsedParticleSystem.id;
  57122. }
  57123. // Auto start
  57124. if (parsedParticleSystem.preventAutoStart) {
  57125. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57126. }
  57127. // Texture
  57128. if (parsedParticleSystem.textureName) {
  57129. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57130. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57131. }
  57132. // Emitter
  57133. if (parsedParticleSystem.emitterId) {
  57134. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57135. }
  57136. else {
  57137. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57138. }
  57139. // Animations
  57140. if (parsedParticleSystem.animations) {
  57141. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57142. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57143. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57144. }
  57145. }
  57146. if (parsedParticleSystem.autoAnimate) {
  57147. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57148. }
  57149. // Particle system
  57150. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57151. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57152. particleSystem.minSize = parsedParticleSystem.minSize;
  57153. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57154. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57155. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57156. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57157. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57158. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57159. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57160. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57161. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57162. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57163. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57164. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57165. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57166. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57167. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57168. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57169. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57170. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57171. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57172. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57173. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57174. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57175. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57176. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57177. if (!particleSystem.preventAutoStart) {
  57178. particleSystem.start();
  57179. }
  57180. return particleSystem;
  57181. };
  57182. /**
  57183. * Source color is added to the destination color without alpha affecting the result.
  57184. */
  57185. ParticleSystem.BLENDMODE_ONEONE = 0;
  57186. /**
  57187. * Blend current color and particle color using particle’s alpha.
  57188. */
  57189. ParticleSystem.BLENDMODE_STANDARD = 1;
  57190. return ParticleSystem;
  57191. }());
  57192. BABYLON.ParticleSystem = ParticleSystem;
  57193. })(BABYLON || (BABYLON = {}));
  57194. //# sourceMappingURL=babylon.particleSystem.js.map
  57195. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57196. var BABYLON;
  57197. (function (BABYLON) {
  57198. /**
  57199. * Particle emitter emitting particles from the inside of a box.
  57200. * It emits the particles randomly between 2 given directions.
  57201. */
  57202. var BoxParticleEmitter = /** @class */ (function () {
  57203. /**
  57204. * Creates a new instance BoxParticleEmitter
  57205. */
  57206. function BoxParticleEmitter() {
  57207. /**
  57208. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57209. */
  57210. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57211. /**
  57212. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57213. */
  57214. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57215. /**
  57216. * 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.
  57217. */
  57218. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57219. /**
  57220. * 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.
  57221. */
  57222. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57223. }
  57224. /**
  57225. * Called by the particle System when the direction is computed for the created particle.
  57226. * @param emitPower is the power of the particle (speed)
  57227. * @param worldMatrix is the world matrix of the particle system
  57228. * @param directionToUpdate is the direction vector to update with the result
  57229. * @param particle is the particle we are computed the direction for
  57230. */
  57231. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57232. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57233. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57234. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57235. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57236. };
  57237. /**
  57238. * Called by the particle System when the position is computed for the created particle.
  57239. * @param worldMatrix is the world matrix of the particle system
  57240. * @param positionToUpdate is the position vector to update with the result
  57241. * @param particle is the particle we are computed the position for
  57242. */
  57243. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57244. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57245. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57246. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57247. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57248. };
  57249. /**
  57250. * Clones the current emitter and returns a copy of it
  57251. * @returns the new emitter
  57252. */
  57253. BoxParticleEmitter.prototype.clone = function () {
  57254. var newOne = new BoxParticleEmitter();
  57255. BABYLON.Tools.DeepCopy(this, newOne);
  57256. return newOne;
  57257. };
  57258. /**
  57259. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57260. * @param effect defines the update shader
  57261. */
  57262. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57263. effect.setVector3("direction1", this.direction1);
  57264. effect.setVector3("direction2", this.direction2);
  57265. effect.setVector3("minEmitBox", this.minEmitBox);
  57266. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57267. };
  57268. /**
  57269. * Returns a string to use to update the GPU particles update shader
  57270. * @returns a string containng the defines string
  57271. */
  57272. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57273. return "#define BOXEMITTER";
  57274. };
  57275. /**
  57276. * Returns the string "BoxEmitter"
  57277. * @returns a string containing the class name
  57278. */
  57279. BoxParticleEmitter.prototype.getClassName = function () {
  57280. return "BoxEmitter";
  57281. };
  57282. /**
  57283. * Serializes the particle system to a JSON object.
  57284. * @returns the JSON object
  57285. */
  57286. BoxParticleEmitter.prototype.serialize = function () {
  57287. var serializationObject = {};
  57288. serializationObject.type = this.getClassName();
  57289. serializationObject.direction1 = this.direction1.asArray();
  57290. serializationObject.direction2 = this.direction2.asArray();
  57291. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57292. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57293. return serializationObject;
  57294. };
  57295. /**
  57296. * Parse properties from a JSON object
  57297. * @param serializationObject defines the JSON object
  57298. */
  57299. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57300. this.direction1.copyFrom(serializationObject.direction1);
  57301. this.direction2.copyFrom(serializationObject.direction2);
  57302. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57303. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57304. };
  57305. return BoxParticleEmitter;
  57306. }());
  57307. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57308. })(BABYLON || (BABYLON = {}));
  57309. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57310. var BABYLON;
  57311. (function (BABYLON) {
  57312. /**
  57313. * Particle emitter emitting particles from the inside of a cone.
  57314. * It emits the particles alongside the cone volume from the base to the particle.
  57315. * The emission direction might be randomized.
  57316. */
  57317. var ConeParticleEmitter = /** @class */ (function () {
  57318. /**
  57319. * Creates a new instance ConeParticleEmitter
  57320. * @param radius the radius of the emission cone (1 by default)
  57321. * @param angles the cone base angle (PI by default)
  57322. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57323. */
  57324. function ConeParticleEmitter(radius,
  57325. /**
  57326. * The radius of the emission cone.
  57327. */
  57328. angle,
  57329. /**
  57330. * The cone base angle.
  57331. */
  57332. directionRandomizer) {
  57333. if (radius === void 0) { radius = 1; }
  57334. if (angle === void 0) { angle = Math.PI; }
  57335. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57336. this.angle = angle;
  57337. this.directionRandomizer = directionRandomizer;
  57338. this.radius = radius;
  57339. }
  57340. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57341. /**
  57342. * Gets the radius of the emission cone.
  57343. */
  57344. get: function () {
  57345. return this._radius;
  57346. },
  57347. /**
  57348. * Sets the radius of the emission cone.
  57349. */
  57350. set: function (value) {
  57351. this._radius = value;
  57352. if (this.angle !== 0) {
  57353. this._height = value / Math.tan(this.angle / 2);
  57354. }
  57355. else {
  57356. this._height = 1;
  57357. }
  57358. },
  57359. enumerable: true,
  57360. configurable: true
  57361. });
  57362. /**
  57363. * Called by the particle System when the direction is computed for the created particle.
  57364. * @param emitPower is the power of the particle (speed)
  57365. * @param worldMatrix is the world matrix of the particle system
  57366. * @param directionToUpdate is the direction vector to update with the result
  57367. * @param particle is the particle we are computed the direction for
  57368. */
  57369. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57370. if (this.angle === 0) {
  57371. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57372. }
  57373. else {
  57374. // measure the direction Vector from the emitter to the particle.
  57375. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57376. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57377. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57378. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57379. direction.x += randX;
  57380. direction.y += randY;
  57381. direction.z += randZ;
  57382. direction.normalize();
  57383. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57384. }
  57385. };
  57386. /**
  57387. * Called by the particle System when the position is computed for the created particle.
  57388. * @param worldMatrix is the world matrix of the particle system
  57389. * @param positionToUpdate is the position vector to update with the result
  57390. * @param particle is the particle we are computed the position for
  57391. */
  57392. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57393. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57394. var h = BABYLON.Scalar.RandomRange(0, 1);
  57395. // Better distribution in a cone at normal angles.
  57396. h = 1 - h * h;
  57397. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57398. radius = radius * h;
  57399. var randX = radius * Math.sin(s);
  57400. var randZ = radius * Math.cos(s);
  57401. var randY = h * this._height;
  57402. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57403. };
  57404. /**
  57405. * Clones the current emitter and returns a copy of it
  57406. * @returns the new emitter
  57407. */
  57408. ConeParticleEmitter.prototype.clone = function () {
  57409. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57410. BABYLON.Tools.DeepCopy(this, newOne);
  57411. return newOne;
  57412. };
  57413. /**
  57414. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57415. * @param effect defines the update shader
  57416. */
  57417. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57418. effect.setFloat("radius", this.radius);
  57419. effect.setFloat("coneAngle", this.angle);
  57420. effect.setFloat("height", this._height);
  57421. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57422. };
  57423. /**
  57424. * Returns a string to use to update the GPU particles update shader
  57425. * @returns a string containng the defines string
  57426. */
  57427. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57428. return "#define CONEEMITTER";
  57429. };
  57430. /**
  57431. * Returns the string "BoxEmitter"
  57432. * @returns a string containing the class name
  57433. */
  57434. ConeParticleEmitter.prototype.getClassName = function () {
  57435. return "ConeEmitter";
  57436. };
  57437. /**
  57438. * Serializes the particle system to a JSON object.
  57439. * @returns the JSON object
  57440. */
  57441. ConeParticleEmitter.prototype.serialize = function () {
  57442. var serializationObject = {};
  57443. serializationObject.type = this.getClassName();
  57444. serializationObject.radius = this.radius;
  57445. serializationObject.angle = this.angle;
  57446. serializationObject.directionRandomizer = this.directionRandomizer;
  57447. return serializationObject;
  57448. };
  57449. /**
  57450. * Parse properties from a JSON object
  57451. * @param serializationObject defines the JSON object
  57452. */
  57453. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57454. this.radius = serializationObject.radius;
  57455. this.angle = serializationObject.angle;
  57456. this.directionRandomizer = serializationObject.directionRandomizer;
  57457. };
  57458. return ConeParticleEmitter;
  57459. }());
  57460. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57461. })(BABYLON || (BABYLON = {}));
  57462. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57463. var BABYLON;
  57464. (function (BABYLON) {
  57465. /**
  57466. * Particle emitter emitting particles from the inside of a sphere.
  57467. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57468. */
  57469. var SphereParticleEmitter = /** @class */ (function () {
  57470. /**
  57471. * Creates a new instance SphereParticleEmitter
  57472. * @param radius the radius of the emission sphere (1 by default)
  57473. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57474. */
  57475. function SphereParticleEmitter(
  57476. /**
  57477. * The radius of the emission sphere.
  57478. */
  57479. radius,
  57480. /**
  57481. * How much to randomize the particle direction [0-1].
  57482. */
  57483. directionRandomizer) {
  57484. if (radius === void 0) { radius = 1; }
  57485. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57486. this.radius = radius;
  57487. this.directionRandomizer = directionRandomizer;
  57488. }
  57489. /**
  57490. * Called by the particle System when the direction is computed for the created particle.
  57491. * @param emitPower is the power of the particle (speed)
  57492. * @param worldMatrix is the world matrix of the particle system
  57493. * @param directionToUpdate is the direction vector to update with the result
  57494. * @param particle is the particle we are computed the direction for
  57495. */
  57496. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57497. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57498. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57499. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57500. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57501. direction.x += randX;
  57502. direction.y += randY;
  57503. direction.z += randZ;
  57504. direction.normalize();
  57505. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57506. };
  57507. /**
  57508. * Called by the particle System when the position is computed for the created particle.
  57509. * @param worldMatrix is the world matrix of the particle system
  57510. * @param positionToUpdate is the position vector to update with the result
  57511. * @param particle is the particle we are computed the position for
  57512. */
  57513. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57514. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57515. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57516. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57517. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57518. var randY = randRadius * Math.cos(theta);
  57519. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57520. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57521. };
  57522. /**
  57523. * Clones the current emitter and returns a copy of it
  57524. * @returns the new emitter
  57525. */
  57526. SphereParticleEmitter.prototype.clone = function () {
  57527. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57528. BABYLON.Tools.DeepCopy(this, newOne);
  57529. return newOne;
  57530. };
  57531. /**
  57532. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57533. * @param effect defines the update shader
  57534. */
  57535. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57536. effect.setFloat("radius", this.radius);
  57537. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57538. };
  57539. /**
  57540. * Returns a string to use to update the GPU particles update shader
  57541. * @returns a string containng the defines string
  57542. */
  57543. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57544. return "#define SPHEREEMITTER";
  57545. };
  57546. /**
  57547. * Returns the string "SphereParticleEmitter"
  57548. * @returns a string containing the class name
  57549. */
  57550. SphereParticleEmitter.prototype.getClassName = function () {
  57551. return "SphereParticleEmitter";
  57552. };
  57553. /**
  57554. * Serializes the particle system to a JSON object.
  57555. * @returns the JSON object
  57556. */
  57557. SphereParticleEmitter.prototype.serialize = function () {
  57558. var serializationObject = {};
  57559. serializationObject.type = this.getClassName();
  57560. serializationObject.radius = this.radius;
  57561. serializationObject.directionRandomizer = this.directionRandomizer;
  57562. return serializationObject;
  57563. };
  57564. /**
  57565. * Parse properties from a JSON object
  57566. * @param serializationObject defines the JSON object
  57567. */
  57568. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57569. this.radius = serializationObject.radius;
  57570. this.directionRandomizer = serializationObject.directionRandomizer;
  57571. };
  57572. return SphereParticleEmitter;
  57573. }());
  57574. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57575. /**
  57576. * Particle emitter emitting particles from the inside of a sphere.
  57577. * It emits the particles randomly between two vectors.
  57578. */
  57579. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57580. __extends(SphereDirectedParticleEmitter, _super);
  57581. /**
  57582. * Creates a new instance SphereDirectedParticleEmitter
  57583. * @param radius the radius of the emission sphere (1 by default)
  57584. * @param direction1 the min limit of the emission direction (up vector by default)
  57585. * @param direction2 the max limit of the emission direction (up vector by default)
  57586. */
  57587. function SphereDirectedParticleEmitter(radius,
  57588. /**
  57589. * The min limit of the emission direction.
  57590. */
  57591. direction1,
  57592. /**
  57593. * The max limit of the emission direction.
  57594. */
  57595. direction2) {
  57596. if (radius === void 0) { radius = 1; }
  57597. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57598. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57599. var _this = _super.call(this, radius) || this;
  57600. _this.direction1 = direction1;
  57601. _this.direction2 = direction2;
  57602. return _this;
  57603. }
  57604. /**
  57605. * Called by the particle System when the direction is computed for the created particle.
  57606. * @param emitPower is the power of the particle (speed)
  57607. * @param worldMatrix is the world matrix of the particle system
  57608. * @param directionToUpdate is the direction vector to update with the result
  57609. * @param particle is the particle we are computed the direction for
  57610. */
  57611. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57612. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57613. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57614. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57615. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57616. };
  57617. /**
  57618. * Clones the current emitter and returns a copy of it
  57619. * @returns the new emitter
  57620. */
  57621. SphereDirectedParticleEmitter.prototype.clone = function () {
  57622. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57623. BABYLON.Tools.DeepCopy(this, newOne);
  57624. return newOne;
  57625. };
  57626. /**
  57627. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57628. * @param effect defines the update shader
  57629. */
  57630. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57631. effect.setFloat("radius", this.radius);
  57632. effect.setVector3("direction1", this.direction1);
  57633. effect.setVector3("direction2", this.direction2);
  57634. };
  57635. /**
  57636. * Returns a string to use to update the GPU particles update shader
  57637. * @returns a string containng the defines string
  57638. */
  57639. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57640. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57641. };
  57642. /**
  57643. * Returns the string "SphereDirectedParticleEmitter"
  57644. * @returns a string containing the class name
  57645. */
  57646. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57647. return "SphereDirectedParticleEmitter";
  57648. };
  57649. /**
  57650. * Serializes the particle system to a JSON object.
  57651. * @returns the JSON object
  57652. */
  57653. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57654. var serializationObject = _super.prototype.serialize.call(this);
  57655. serializationObject.direction1 = this.direction1.asArray();
  57656. serializationObject.direction2 = this.direction2.asArray();
  57657. return serializationObject;
  57658. };
  57659. /**
  57660. * Parse properties from a JSON object
  57661. * @param serializationObject defines the JSON object
  57662. */
  57663. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57664. _super.prototype.parse.call(this, serializationObject);
  57665. this.direction1.copyFrom(serializationObject.direction1);
  57666. this.direction2.copyFrom(serializationObject.direction2);
  57667. };
  57668. return SphereDirectedParticleEmitter;
  57669. }(SphereParticleEmitter));
  57670. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57671. })(BABYLON || (BABYLON = {}));
  57672. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57673. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57674. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57675. s = arguments[i];
  57676. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57677. t[p] = s[p];
  57678. }
  57679. return t;
  57680. };
  57681. var BABYLON;
  57682. (function (BABYLON) {
  57683. /**
  57684. * This represents a GPU particle system in Babylon
  57685. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57686. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57687. */
  57688. var GPUParticleSystem = /** @class */ (function () {
  57689. /**
  57690. * Instantiates a GPU particle system.
  57691. * 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.
  57692. * @param name The name of the particle system
  57693. * @param capacity The max number of particles alive at the same time
  57694. * @param scene The scene the particle system belongs to
  57695. */
  57696. function GPUParticleSystem(name, options, scene) {
  57697. /**
  57698. * The emitter represents the Mesh or position we are attaching the particle system to.
  57699. */
  57700. this.emitter = null;
  57701. /**
  57702. * The rendering group used by the Particle system to chose when to render.
  57703. */
  57704. this.renderingGroupId = 0;
  57705. /**
  57706. * The layer mask we are rendering the particles through.
  57707. */
  57708. this.layerMask = 0x0FFFFFFF;
  57709. this._targetIndex = 0;
  57710. this._currentRenderId = -1;
  57711. this._started = false;
  57712. this._stopped = false;
  57713. this._timeDelta = 0;
  57714. this._attributesStrideSize = 16;
  57715. this._actualFrame = 0;
  57716. /**
  57717. * List of animations used by the particle system.
  57718. */
  57719. this.animations = [];
  57720. /**
  57721. * An event triggered when the system is disposed.
  57722. */
  57723. this.onDisposeObservable = new BABYLON.Observable();
  57724. /**
  57725. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57726. */
  57727. this.updateSpeed = 0.01;
  57728. /**
  57729. * The amount of time the particle system is running (depends of the overall update speed).
  57730. */
  57731. this.targetStopDuration = 0;
  57732. /**
  57733. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57734. */
  57735. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57736. /**
  57737. * Minimum life time of emitting particles.
  57738. */
  57739. this.minLifeTime = 1;
  57740. /**
  57741. * Maximum life time of emitting particles.
  57742. */
  57743. this.maxLifeTime = 1;
  57744. /**
  57745. * Minimum Size of emitting particles.
  57746. */
  57747. this.minSize = 1;
  57748. /**
  57749. * Maximum Size of emitting particles.
  57750. */
  57751. this.maxSize = 1;
  57752. /**
  57753. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57754. */
  57755. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57756. /**
  57757. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57758. */
  57759. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57760. /**
  57761. * Color the particle will have at the end of its lifetime.
  57762. */
  57763. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57764. /**
  57765. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57766. */
  57767. this.emitRate = 100;
  57768. /**
  57769. * You can use gravity if you want to give an orientation to your particles.
  57770. */
  57771. this.gravity = BABYLON.Vector3.Zero();
  57772. /**
  57773. * Minimum power of emitting particles.
  57774. */
  57775. this.minEmitPower = 1;
  57776. /**
  57777. * Maximum power of emitting particles.
  57778. */
  57779. this.maxEmitPower = 1;
  57780. /**
  57781. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57782. */
  57783. this.minAngularSpeed = 0;
  57784. /**
  57785. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57786. */
  57787. this.maxAngularSpeed = 0;
  57788. /**
  57789. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57790. * to override the particles.
  57791. */
  57792. this.forceDepthWrite = false;
  57793. this.id = name;
  57794. this.name = name;
  57795. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57796. this._engine = this._scene.getEngine();
  57797. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57798. this._capacity = fullOptions.capacity;
  57799. this._activeCount = fullOptions.capacity;
  57800. this._currentActiveCount = 0;
  57801. this._scene.particleSystems.push(this);
  57802. this._updateEffectOptions = {
  57803. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57804. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57805. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57806. "angleRange"],
  57807. uniformBuffersNames: [],
  57808. samplers: ["randomSampler"],
  57809. defines: "",
  57810. fallbacks: null,
  57811. onCompiled: null,
  57812. onError: null,
  57813. indexParameters: null,
  57814. maxSimultaneousLights: 0,
  57815. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57816. };
  57817. // Random data
  57818. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57819. var d = [];
  57820. for (var i = 0; i < maxTextureSize; ++i) {
  57821. d.push(Math.random());
  57822. d.push(Math.random());
  57823. d.push(Math.random());
  57824. d.push(Math.random());
  57825. }
  57826. 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);
  57827. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57828. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57829. this._randomTextureSize = maxTextureSize;
  57830. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57831. }
  57832. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57833. /**
  57834. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57835. */
  57836. get: function () {
  57837. if (!BABYLON.Engine.LastCreatedEngine) {
  57838. return false;
  57839. }
  57840. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57841. },
  57842. enumerable: true,
  57843. configurable: true
  57844. });
  57845. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57846. /**
  57847. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57848. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57849. */
  57850. get: function () {
  57851. if (this.particleEmitterType.direction1) {
  57852. return this.particleEmitterType.direction1;
  57853. }
  57854. return BABYLON.Vector3.Zero();
  57855. },
  57856. set: function (value) {
  57857. if (this.particleEmitterType.direction1) {
  57858. this.particleEmitterType.direction1 = value;
  57859. }
  57860. },
  57861. enumerable: true,
  57862. configurable: true
  57863. });
  57864. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57865. /**
  57866. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57867. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57868. */
  57869. get: function () {
  57870. if (this.particleEmitterType.direction2) {
  57871. return this.particleEmitterType.direction2;
  57872. }
  57873. return BABYLON.Vector3.Zero();
  57874. },
  57875. set: function (value) {
  57876. if (this.particleEmitterType.direction2) {
  57877. this.particleEmitterType.direction2 = value;
  57878. }
  57879. },
  57880. enumerable: true,
  57881. configurable: true
  57882. });
  57883. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57884. /**
  57885. * 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.
  57886. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57887. */
  57888. get: function () {
  57889. if (this.particleEmitterType.minEmitBox) {
  57890. return this.particleEmitterType.minEmitBox;
  57891. }
  57892. return BABYLON.Vector3.Zero();
  57893. },
  57894. set: function (value) {
  57895. if (this.particleEmitterType.minEmitBox) {
  57896. this.particleEmitterType.minEmitBox = value;
  57897. }
  57898. },
  57899. enumerable: true,
  57900. configurable: true
  57901. });
  57902. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57903. /**
  57904. * 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.
  57905. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57906. */
  57907. get: function () {
  57908. if (this.particleEmitterType.maxEmitBox) {
  57909. return this.particleEmitterType.maxEmitBox;
  57910. }
  57911. return BABYLON.Vector3.Zero();
  57912. },
  57913. set: function (value) {
  57914. if (this.particleEmitterType.maxEmitBox) {
  57915. this.particleEmitterType.maxEmitBox = value;
  57916. }
  57917. },
  57918. enumerable: true,
  57919. configurable: true
  57920. });
  57921. /**
  57922. * Gets the maximum number of particles active at the same time.
  57923. * @returns The max number of active particles.
  57924. */
  57925. GPUParticleSystem.prototype.getCapacity = function () {
  57926. return this._capacity;
  57927. };
  57928. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57929. /**
  57930. * Gets or set the number of active particles
  57931. */
  57932. get: function () {
  57933. return this._activeCount;
  57934. },
  57935. set: function (value) {
  57936. this._activeCount = Math.min(value, this._capacity);
  57937. },
  57938. enumerable: true,
  57939. configurable: true
  57940. });
  57941. /**
  57942. * Is this system ready to be used/rendered
  57943. * @return true if the system is ready
  57944. */
  57945. GPUParticleSystem.prototype.isReady = function () {
  57946. if (!this._updateEffect) {
  57947. this._recreateUpdateEffect();
  57948. this._recreateRenderEffect();
  57949. return false;
  57950. }
  57951. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57952. return false;
  57953. }
  57954. return true;
  57955. };
  57956. /**
  57957. * Gets Wether the system has been started.
  57958. * @returns True if it has been started, otherwise false.
  57959. */
  57960. GPUParticleSystem.prototype.isStarted = function () {
  57961. return this._started;
  57962. };
  57963. /**
  57964. * Starts the particle system and begins to emit.
  57965. */
  57966. GPUParticleSystem.prototype.start = function () {
  57967. this._started = true;
  57968. this._stopped = false;
  57969. };
  57970. /**
  57971. * Stops the particle system.
  57972. */
  57973. GPUParticleSystem.prototype.stop = function () {
  57974. this._stopped = true;
  57975. };
  57976. /**
  57977. * Remove all active particles
  57978. */
  57979. GPUParticleSystem.prototype.reset = function () {
  57980. this._releaseBuffers();
  57981. this._releaseVAOs();
  57982. this._currentActiveCount = 0;
  57983. this._targetIndex = 0;
  57984. };
  57985. /**
  57986. * Returns the string "GPUParticleSystem"
  57987. * @returns a string containing the class name
  57988. */
  57989. GPUParticleSystem.prototype.getClassName = function () {
  57990. return "GPUParticleSystem";
  57991. };
  57992. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57993. var updateVertexBuffers = {};
  57994. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57995. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57996. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57997. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57998. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57999. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  58000. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  58001. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  58002. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  58003. this._engine.bindArrayBuffer(null);
  58004. return vao;
  58005. };
  58006. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  58007. var renderVertexBuffers = {};
  58008. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  58009. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  58010. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  58011. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  58012. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  58013. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  58014. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  58015. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  58016. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  58017. this._engine.bindArrayBuffer(null);
  58018. return vao;
  58019. };
  58020. GPUParticleSystem.prototype._initialize = function (force) {
  58021. if (force === void 0) { force = false; }
  58022. if (this._buffer0 && !force) {
  58023. return;
  58024. }
  58025. var engine = this._scene.getEngine();
  58026. var data = new Array();
  58027. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  58028. // position
  58029. data.push(0.0);
  58030. data.push(0.0);
  58031. data.push(0.0);
  58032. // Age and life
  58033. data.push(0.0); // create the particle as a dead one to create a new one at start
  58034. data.push(0.0);
  58035. // Seed
  58036. data.push(Math.random());
  58037. // Size
  58038. data.push(0.0);
  58039. // color
  58040. data.push(0.0);
  58041. data.push(0.0);
  58042. data.push(0.0);
  58043. data.push(0.0);
  58044. // direction
  58045. data.push(0.0);
  58046. data.push(0.0);
  58047. data.push(0.0);
  58048. // angle
  58049. data.push(0.0);
  58050. data.push(0.0);
  58051. }
  58052. // Sprite data
  58053. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  58054. -0.5, 0.5, 0, 1,
  58055. -0.5, -0.5, 0, 0,
  58056. 0.5, -0.5, 1, 0]);
  58057. // Buffers
  58058. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58059. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58060. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  58061. // Update VAO
  58062. this._updateVAO = [];
  58063. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  58064. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  58065. // Render VAO
  58066. this._renderVAO = [];
  58067. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  58068. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  58069. // Links
  58070. this._sourceBuffer = this._buffer0;
  58071. this._targetBuffer = this._buffer1;
  58072. };
  58073. /** @hidden */
  58074. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  58075. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  58076. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  58077. return;
  58078. }
  58079. this._updateEffectOptions.defines = defines;
  58080. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  58081. };
  58082. /** @hidden */
  58083. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  58084. var defines = "";
  58085. if (this._scene.clipPlane) {
  58086. defines = "\n#define CLIPPLANE";
  58087. }
  58088. if (this._renderEffect && this._renderEffect.defines === defines) {
  58089. return;
  58090. }
  58091. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  58092. };
  58093. /**
  58094. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58095. */
  58096. GPUParticleSystem.prototype.animate = function () {
  58097. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  58098. this._actualFrame += this._timeDelta;
  58099. if (!this._stopped) {
  58100. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58101. this.stop();
  58102. }
  58103. }
  58104. };
  58105. /**
  58106. * Renders the particle system in its current state.
  58107. * @returns the current number of particles
  58108. */
  58109. GPUParticleSystem.prototype.render = function () {
  58110. if (!this._started) {
  58111. return 0;
  58112. }
  58113. this._recreateUpdateEffect();
  58114. this._recreateRenderEffect();
  58115. if (!this.isReady()) {
  58116. return 0;
  58117. }
  58118. if (this._currentRenderId === this._scene.getRenderId()) {
  58119. return 0;
  58120. }
  58121. this._currentRenderId = this._scene.getRenderId();
  58122. // Get everything ready to render
  58123. this._initialize();
  58124. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  58125. // Enable update effect
  58126. this._engine.enableEffect(this._updateEffect);
  58127. this._engine.setState(false);
  58128. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58129. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58130. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58131. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  58132. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58133. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58134. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58135. this._updateEffect.setDirectColor4("color1", this.color1);
  58136. this._updateEffect.setDirectColor4("color2", this.color2);
  58137. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58138. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  58139. this._updateEffect.setVector3("gravity", this.gravity);
  58140. if (this.particleEmitterType) {
  58141. this.particleEmitterType.applyToShader(this._updateEffect);
  58142. }
  58143. var emitterWM;
  58144. if (this.emitter.position) {
  58145. var emitterMesh = this.emitter;
  58146. emitterWM = emitterMesh.getWorldMatrix();
  58147. }
  58148. else {
  58149. var emitterPosition = this.emitter;
  58150. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58151. }
  58152. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58153. // Bind source VAO
  58154. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58155. // Update
  58156. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58157. this._engine.setRasterizerState(false);
  58158. this._engine.beginTransformFeedback();
  58159. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58160. this._engine.endTransformFeedback();
  58161. this._engine.setRasterizerState(true);
  58162. this._engine.bindTransformFeedbackBuffer(null);
  58163. // Enable render effect
  58164. this._engine.enableEffect(this._renderEffect);
  58165. var viewMatrix = this._scene.getViewMatrix();
  58166. this._renderEffect.setMatrix("view", viewMatrix);
  58167. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58168. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58169. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58170. if (this._scene.clipPlane) {
  58171. var clipPlane = this._scene.clipPlane;
  58172. var invView = viewMatrix.clone();
  58173. invView.invert();
  58174. this._renderEffect.setMatrix("invView", invView);
  58175. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58176. }
  58177. // Draw order
  58178. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58179. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58180. }
  58181. else {
  58182. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58183. }
  58184. if (this.forceDepthWrite) {
  58185. this._engine.setDepthWrite(true);
  58186. }
  58187. // Bind source VAO
  58188. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58189. // Render
  58190. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58191. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58192. // Switch VAOs
  58193. this._targetIndex++;
  58194. if (this._targetIndex === 2) {
  58195. this._targetIndex = 0;
  58196. }
  58197. // Switch buffers
  58198. var tmpBuffer = this._sourceBuffer;
  58199. this._sourceBuffer = this._targetBuffer;
  58200. this._targetBuffer = tmpBuffer;
  58201. return this._currentActiveCount;
  58202. };
  58203. /**
  58204. * Rebuilds the particle system
  58205. */
  58206. GPUParticleSystem.prototype.rebuild = function () {
  58207. this._initialize(true);
  58208. };
  58209. GPUParticleSystem.prototype._releaseBuffers = function () {
  58210. if (this._buffer0) {
  58211. this._buffer0.dispose();
  58212. this._buffer0 = null;
  58213. }
  58214. if (this._buffer1) {
  58215. this._buffer1.dispose();
  58216. this._buffer1 = null;
  58217. }
  58218. if (this._spriteBuffer) {
  58219. this._spriteBuffer.dispose();
  58220. this._spriteBuffer = null;
  58221. }
  58222. };
  58223. GPUParticleSystem.prototype._releaseVAOs = function () {
  58224. if (!this._updateVAO) {
  58225. return;
  58226. }
  58227. for (var index = 0; index < this._updateVAO.length; index++) {
  58228. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58229. }
  58230. this._updateVAO = [];
  58231. for (var index = 0; index < this._renderVAO.length; index++) {
  58232. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58233. }
  58234. this._renderVAO = [];
  58235. };
  58236. /**
  58237. * Disposes the particle system and free the associated resources
  58238. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58239. */
  58240. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58241. if (disposeTexture === void 0) { disposeTexture = true; }
  58242. var index = this._scene.particleSystems.indexOf(this);
  58243. if (index > -1) {
  58244. this._scene.particleSystems.splice(index, 1);
  58245. }
  58246. this._releaseBuffers();
  58247. this._releaseVAOs();
  58248. if (this._randomTexture) {
  58249. this._randomTexture.dispose();
  58250. this._randomTexture = null;
  58251. }
  58252. if (disposeTexture && this.particleTexture) {
  58253. this.particleTexture.dispose();
  58254. this.particleTexture = null;
  58255. }
  58256. // Callback
  58257. this.onDisposeObservable.notifyObservers(this);
  58258. this.onDisposeObservable.clear();
  58259. };
  58260. /**
  58261. * Clones the particle system.
  58262. * @param name The name of the cloned object
  58263. * @param newEmitter The new emitter to use
  58264. * @returns the cloned particle system
  58265. */
  58266. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58267. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58268. BABYLON.Tools.DeepCopy(this, result);
  58269. if (newEmitter === undefined) {
  58270. newEmitter = this.emitter;
  58271. }
  58272. result.emitter = newEmitter;
  58273. if (this.particleTexture) {
  58274. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58275. }
  58276. return result;
  58277. };
  58278. /**
  58279. * Serializes the particle system to a JSON object.
  58280. * @returns the JSON object
  58281. */
  58282. GPUParticleSystem.prototype.serialize = function () {
  58283. var serializationObject = {};
  58284. serializationObject.name = this.name;
  58285. serializationObject.id = this.id;
  58286. // Emitter
  58287. if (this.emitter.position) {
  58288. var emitterMesh = this.emitter;
  58289. serializationObject.emitterId = emitterMesh.id;
  58290. }
  58291. else {
  58292. var emitterPosition = this.emitter;
  58293. serializationObject.emitter = emitterPosition.asArray();
  58294. }
  58295. serializationObject.capacity = this.getCapacity();
  58296. if (this.particleTexture) {
  58297. serializationObject.textureName = this.particleTexture.name;
  58298. }
  58299. // Animations
  58300. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58301. // Particle system
  58302. serializationObject.activeParticleCount = this.activeParticleCount;
  58303. serializationObject.randomTextureSize = this._randomTextureSize;
  58304. serializationObject.minSize = this.minSize;
  58305. serializationObject.maxSize = this.maxSize;
  58306. serializationObject.minEmitPower = this.minEmitPower;
  58307. serializationObject.maxEmitPower = this.maxEmitPower;
  58308. serializationObject.minLifeTime = this.minLifeTime;
  58309. serializationObject.maxLifeTime = this.maxLifeTime;
  58310. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58311. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58312. serializationObject.emitRate = this.emitRate;
  58313. serializationObject.gravity = this.gravity.asArray();
  58314. serializationObject.color1 = this.color1.asArray();
  58315. serializationObject.color2 = this.color2.asArray();
  58316. serializationObject.colorDead = this.colorDead.asArray();
  58317. serializationObject.updateSpeed = this.updateSpeed;
  58318. serializationObject.targetStopDuration = this.targetStopDuration;
  58319. serializationObject.blendMode = this.blendMode;
  58320. // Emitter
  58321. if (this.particleEmitterType) {
  58322. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58323. }
  58324. return serializationObject;
  58325. };
  58326. /**
  58327. * Parses a JSON object to create a GPU particle system.
  58328. * @param parsedParticleSystem The JSON object to parse
  58329. * @param scene The scene to create the particle system in
  58330. * @param rootUrl The root url to use to load external dependencies like texture
  58331. * @returns the parsed GPU particle system
  58332. */
  58333. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58334. var name = parsedParticleSystem.name;
  58335. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58336. if (parsedParticleSystem.id) {
  58337. particleSystem.id = parsedParticleSystem.id;
  58338. }
  58339. // Texture
  58340. if (parsedParticleSystem.textureName) {
  58341. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58342. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58343. }
  58344. // Emitter
  58345. if (parsedParticleSystem.emitterId) {
  58346. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58347. }
  58348. else {
  58349. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58350. }
  58351. // Animations
  58352. if (parsedParticleSystem.animations) {
  58353. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58354. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58355. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58356. }
  58357. }
  58358. // Particle system
  58359. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58360. particleSystem.minSize = parsedParticleSystem.minSize;
  58361. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58362. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58363. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58364. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58365. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58366. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58367. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58368. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58369. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58370. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58371. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58372. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58373. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58374. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58375. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58376. // Emitter
  58377. if (parsedParticleSystem.particleEmitterType) {
  58378. var emitterType = void 0;
  58379. switch (parsedParticleSystem.particleEmitterType.type) {
  58380. case "SphereEmitter":
  58381. emitterType = new BABYLON.SphereParticleEmitter();
  58382. break;
  58383. case "SphereDirectedParticleEmitter":
  58384. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58385. break;
  58386. case "ConeEmitter":
  58387. emitterType = new BABYLON.ConeParticleEmitter();
  58388. break;
  58389. case "BoxEmitter":
  58390. default:
  58391. emitterType = new BABYLON.BoxParticleEmitter();
  58392. break;
  58393. }
  58394. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58395. particleSystem.particleEmitterType = emitterType;
  58396. }
  58397. return particleSystem;
  58398. };
  58399. return GPUParticleSystem;
  58400. }());
  58401. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58402. })(BABYLON || (BABYLON = {}));
  58403. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58404. var BABYLON;
  58405. (function (BABYLON) {
  58406. /**
  58407. * Represents one particle of a solid particle system.
  58408. */
  58409. var SolidParticle = /** @class */ (function () {
  58410. /**
  58411. * Creates a Solid Particle object.
  58412. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58413. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58414. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58415. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58416. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58417. * @param shapeId (integer) is the model shape identifier in the SPS.
  58418. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58419. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58420. */
  58421. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58422. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58423. /**
  58424. * particle global index
  58425. */
  58426. this.idx = 0;
  58427. /**
  58428. * The color of the particle
  58429. */
  58430. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58431. /**
  58432. * The world space position of the particle.
  58433. */
  58434. this.position = BABYLON.Vector3.Zero();
  58435. /**
  58436. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58437. */
  58438. this.rotation = BABYLON.Vector3.Zero();
  58439. /**
  58440. * The scaling of the particle.
  58441. */
  58442. this.scaling = BABYLON.Vector3.One();
  58443. /**
  58444. * The uvs of the particle.
  58445. */
  58446. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58447. /**
  58448. * The current speed of the particle.
  58449. */
  58450. this.velocity = BABYLON.Vector3.Zero();
  58451. /**
  58452. * The pivot point in the particle local space.
  58453. */
  58454. this.pivot = BABYLON.Vector3.Zero();
  58455. /**
  58456. * Must the particle be translated from its pivot point in its local space ?
  58457. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58458. * Default : false
  58459. */
  58460. this.translateFromPivot = false;
  58461. /**
  58462. * Is the particle active or not ?
  58463. */
  58464. this.alive = true;
  58465. /**
  58466. * Is the particle visible or not ?
  58467. */
  58468. this.isVisible = true;
  58469. /**
  58470. * Index of this particle in the global "positions" array (Internal use)
  58471. */
  58472. this._pos = 0;
  58473. /**
  58474. * Index of this particle in the global "indices" array (Internal use)
  58475. */
  58476. this._ind = 0;
  58477. /**
  58478. * ModelShape id of this particle
  58479. */
  58480. this.shapeId = 0;
  58481. /**
  58482. * Index of the particle in its shape id (Internal use)
  58483. */
  58484. this.idxInShape = 0;
  58485. /**
  58486. * Still set as invisible in order to skip useless computations (Internal use)
  58487. */
  58488. this._stillInvisible = false;
  58489. /**
  58490. * Last computed particle rotation matrix
  58491. */
  58492. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58493. /**
  58494. * Parent particle Id, if any.
  58495. * Default null.
  58496. */
  58497. this.parentId = null;
  58498. /**
  58499. * Internal global position in the SPS.
  58500. */
  58501. this._globalPosition = BABYLON.Vector3.Zero();
  58502. this.idx = particleIndex;
  58503. this._pos = positionIndex;
  58504. this._ind = indiceIndex;
  58505. this._model = model;
  58506. this.shapeId = shapeId;
  58507. this.idxInShape = idxInShape;
  58508. this._sps = sps;
  58509. if (modelBoundingInfo) {
  58510. this._modelBoundingInfo = modelBoundingInfo;
  58511. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58512. }
  58513. }
  58514. Object.defineProperty(SolidParticle.prototype, "scale", {
  58515. /**
  58516. * Legacy support, changed scale to scaling
  58517. */
  58518. get: function () {
  58519. return this.scaling;
  58520. },
  58521. /**
  58522. * Legacy support, changed scale to scaling
  58523. */
  58524. set: function (scale) {
  58525. this.scaling = scale;
  58526. },
  58527. enumerable: true,
  58528. configurable: true
  58529. });
  58530. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58531. /**
  58532. * Legacy support, changed quaternion to rotationQuaternion
  58533. */
  58534. get: function () {
  58535. return this.rotationQuaternion;
  58536. },
  58537. /**
  58538. * Legacy support, changed quaternion to rotationQuaternion
  58539. */
  58540. set: function (q) {
  58541. this.rotationQuaternion = q;
  58542. },
  58543. enumerable: true,
  58544. configurable: true
  58545. });
  58546. /**
  58547. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58548. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58549. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58550. * @returns true if it intersects
  58551. */
  58552. SolidParticle.prototype.intersectsMesh = function (target) {
  58553. if (!this._boundingInfo || !target._boundingInfo) {
  58554. return false;
  58555. }
  58556. if (this._sps._bSphereOnly) {
  58557. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58558. }
  58559. return this._boundingInfo.intersects(target._boundingInfo, false);
  58560. };
  58561. return SolidParticle;
  58562. }());
  58563. BABYLON.SolidParticle = SolidParticle;
  58564. /**
  58565. * Represents the shape of the model used by one particle of a solid particle system.
  58566. * SPS internal tool, don't use it manually.
  58567. */
  58568. var ModelShape = /** @class */ (function () {
  58569. /**
  58570. * 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.
  58571. * SPS internal tool, don't use it manually.
  58572. * @hidden
  58573. */
  58574. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58575. /**
  58576. * length of the shape in the model indices array (internal use)
  58577. */
  58578. this._indicesLength = 0;
  58579. this.shapeID = id;
  58580. this._shape = shape;
  58581. this._indicesLength = indicesLength;
  58582. this._shapeUV = shapeUV;
  58583. this._positionFunction = posFunction;
  58584. this._vertexFunction = vtxFunction;
  58585. }
  58586. return ModelShape;
  58587. }());
  58588. BABYLON.ModelShape = ModelShape;
  58589. /**
  58590. * Represents a Depth Sorted Particle in the solid particle system.
  58591. */
  58592. var DepthSortedParticle = /** @class */ (function () {
  58593. function DepthSortedParticle() {
  58594. /**
  58595. * Index of the particle in the "indices" array
  58596. */
  58597. this.ind = 0;
  58598. /**
  58599. * Length of the particle shape in the "indices" array
  58600. */
  58601. this.indicesLength = 0;
  58602. /**
  58603. * Squared distance from the particle to the camera
  58604. */
  58605. this.sqDistance = 0.0;
  58606. }
  58607. return DepthSortedParticle;
  58608. }());
  58609. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58610. })(BABYLON || (BABYLON = {}));
  58611. //# sourceMappingURL=babylon.solidParticle.js.map
  58612. var BABYLON;
  58613. (function (BABYLON) {
  58614. /**
  58615. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58616. *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.
  58617. * The SPS is also a particle system. It provides some methods to manage the particles.
  58618. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58619. *
  58620. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58621. */
  58622. var SolidParticleSystem = /** @class */ (function () {
  58623. /**
  58624. * Creates a SPS (Solid Particle System) object.
  58625. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58626. * @param scene (Scene) is the scene in which the SPS is added.
  58627. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58628. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58629. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58630. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58631. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58632. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58633. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58634. */
  58635. function SolidParticleSystem(name, scene, options) {
  58636. /**
  58637. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58638. * Example : var p = SPS.particles[i];
  58639. */
  58640. this.particles = new Array();
  58641. /**
  58642. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58643. */
  58644. this.nbParticles = 0;
  58645. /**
  58646. * If the particles must ever face the camera (default false). Useful for planar particles.
  58647. */
  58648. this.billboard = false;
  58649. /**
  58650. * Recompute normals when adding a shape
  58651. */
  58652. this.recomputeNormals = true;
  58653. /**
  58654. * This a counter ofr your own usage. It's not set by any SPS functions.
  58655. */
  58656. this.counter = 0;
  58657. /**
  58658. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58659. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58660. */
  58661. this.vars = {};
  58662. /**
  58663. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58664. */
  58665. this._bSphereOnly = false;
  58666. /**
  58667. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58668. */
  58669. this._bSphereRadiusFactor = 1.0;
  58670. this._positions = new Array();
  58671. this._indices = new Array();
  58672. this._normals = new Array();
  58673. this._colors = new Array();
  58674. this._uvs = new Array();
  58675. this._index = 0; // indices index
  58676. this._updatable = true;
  58677. this._pickable = false;
  58678. this._isVisibilityBoxLocked = false;
  58679. this._alwaysVisible = false;
  58680. this._depthSort = false;
  58681. this._shapeCounter = 0;
  58682. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58683. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58684. this._computeParticleColor = true;
  58685. this._computeParticleTexture = true;
  58686. this._computeParticleRotation = true;
  58687. this._computeParticleVertex = false;
  58688. this._computeBoundingBox = false;
  58689. this._depthSortParticles = true;
  58690. this._cam_axisZ = BABYLON.Vector3.Zero();
  58691. this._cam_axisY = BABYLON.Vector3.Zero();
  58692. this._cam_axisX = BABYLON.Vector3.Zero();
  58693. this._axisZ = BABYLON.Axis.Z;
  58694. this._camDir = BABYLON.Vector3.Zero();
  58695. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58696. this._rotMatrix = new BABYLON.Matrix();
  58697. this._invertMatrix = new BABYLON.Matrix();
  58698. this._rotated = BABYLON.Vector3.Zero();
  58699. this._quaternion = new BABYLON.Quaternion();
  58700. this._vertex = BABYLON.Vector3.Zero();
  58701. this._normal = BABYLON.Vector3.Zero();
  58702. this._yaw = 0.0;
  58703. this._pitch = 0.0;
  58704. this._roll = 0.0;
  58705. this._halfroll = 0.0;
  58706. this._halfpitch = 0.0;
  58707. this._halfyaw = 0.0;
  58708. this._sinRoll = 0.0;
  58709. this._cosRoll = 0.0;
  58710. this._sinPitch = 0.0;
  58711. this._cosPitch = 0.0;
  58712. this._sinYaw = 0.0;
  58713. this._cosYaw = 0.0;
  58714. this._mustUnrotateFixedNormals = false;
  58715. this._minimum = BABYLON.Vector3.Zero();
  58716. this._maximum = BABYLON.Vector3.Zero();
  58717. this._minBbox = BABYLON.Vector3.Zero();
  58718. this._maxBbox = BABYLON.Vector3.Zero();
  58719. this._particlesIntersect = false;
  58720. this._depthSortFunction = function (p1, p2) {
  58721. return (p2.sqDistance - p1.sqDistance);
  58722. };
  58723. this._needs32Bits = false;
  58724. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58725. this._scaledPivot = BABYLON.Vector3.Zero();
  58726. this._particleHasParent = false;
  58727. this.name = name;
  58728. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58729. this._camera = scene.activeCamera;
  58730. this._pickable = options ? options.isPickable : false;
  58731. this._depthSort = options ? options.enableDepthSort : false;
  58732. this._particlesIntersect = options ? options.particleIntersection : false;
  58733. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58734. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58735. if (options && options.updatable) {
  58736. this._updatable = options.updatable;
  58737. }
  58738. else {
  58739. this._updatable = true;
  58740. }
  58741. if (this._pickable) {
  58742. this.pickedParticles = [];
  58743. }
  58744. if (this._depthSort) {
  58745. this.depthSortedParticles = [];
  58746. }
  58747. }
  58748. /**
  58749. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58750. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58751. * @returns the created mesh
  58752. */
  58753. SolidParticleSystem.prototype.buildMesh = function () {
  58754. if (this.nbParticles === 0) {
  58755. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58756. this.addShape(triangle, 1);
  58757. triangle.dispose();
  58758. }
  58759. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58760. this._positions32 = new Float32Array(this._positions);
  58761. this._uvs32 = new Float32Array(this._uvs);
  58762. this._colors32 = new Float32Array(this._colors);
  58763. if (this.recomputeNormals) {
  58764. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58765. }
  58766. this._normals32 = new Float32Array(this._normals);
  58767. this._fixedNormal32 = new Float32Array(this._normals);
  58768. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58769. this._unrotateFixedNormals();
  58770. }
  58771. var vertexData = new BABYLON.VertexData();
  58772. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58773. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58774. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58775. if (this._uvs32.length > 0) {
  58776. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58777. }
  58778. if (this._colors32.length > 0) {
  58779. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58780. }
  58781. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58782. vertexData.applyToMesh(mesh, this._updatable);
  58783. this.mesh = mesh;
  58784. this.mesh.isPickable = this._pickable;
  58785. // free memory
  58786. if (!this._depthSort) {
  58787. this._indices = null;
  58788. }
  58789. this._positions = null;
  58790. this._normals = null;
  58791. this._uvs = null;
  58792. this._colors = null;
  58793. if (!this._updatable) {
  58794. this.particles.length = 0;
  58795. }
  58796. return mesh;
  58797. };
  58798. /**
  58799. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58800. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58801. * Thus the particles generated from `digest()` have their property `position` set yet.
  58802. * @param mesh ( Mesh ) is the mesh to be digested
  58803. * @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
  58804. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58805. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58806. * @returns the current SPS
  58807. */
  58808. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58809. var size = (options && options.facetNb) || 1;
  58810. var number = (options && options.number) || 0;
  58811. var delta = (options && options.delta) || 0;
  58812. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58813. var meshInd = mesh.getIndices();
  58814. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58815. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58816. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58817. var f = 0; // facet counter
  58818. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58819. // compute size from number
  58820. if (number) {
  58821. number = (number > totalFacets) ? totalFacets : number;
  58822. size = Math.round(totalFacets / number);
  58823. delta = 0;
  58824. }
  58825. else {
  58826. size = (size > totalFacets) ? totalFacets : size;
  58827. }
  58828. var facetPos = []; // submesh positions
  58829. var facetInd = []; // submesh indices
  58830. var facetUV = []; // submesh UV
  58831. var facetCol = []; // submesh colors
  58832. var barycenter = BABYLON.Vector3.Zero();
  58833. var sizeO = size;
  58834. while (f < totalFacets) {
  58835. size = sizeO + Math.floor((1 + delta) * Math.random());
  58836. if (f > totalFacets - size) {
  58837. size = totalFacets - f;
  58838. }
  58839. // reset temp arrays
  58840. facetPos.length = 0;
  58841. facetInd.length = 0;
  58842. facetUV.length = 0;
  58843. facetCol.length = 0;
  58844. // iterate over "size" facets
  58845. var fi = 0;
  58846. for (var j = f * 3; j < (f + size) * 3; j++) {
  58847. facetInd.push(fi);
  58848. var i = meshInd[j];
  58849. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58850. if (meshUV) {
  58851. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58852. }
  58853. if (meshCol) {
  58854. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58855. }
  58856. fi++;
  58857. }
  58858. // create a model shape for each single particle
  58859. var idx = this.nbParticles;
  58860. var shape = this._posToShape(facetPos);
  58861. var shapeUV = this._uvsToShapeUV(facetUV);
  58862. // compute the barycenter of the shape
  58863. var v;
  58864. for (v = 0; v < shape.length; v++) {
  58865. barycenter.addInPlace(shape[v]);
  58866. }
  58867. barycenter.scaleInPlace(1 / shape.length);
  58868. // shift the shape from its barycenter to the origin
  58869. for (v = 0; v < shape.length; v++) {
  58870. shape[v].subtractInPlace(barycenter);
  58871. }
  58872. var bInfo;
  58873. if (this._particlesIntersect) {
  58874. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58875. }
  58876. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58877. // add the particle in the SPS
  58878. var currentPos = this._positions.length;
  58879. var currentInd = this._indices.length;
  58880. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58881. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58882. // initialize the particle position
  58883. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58884. this._index += shape.length;
  58885. idx++;
  58886. this.nbParticles++;
  58887. this._shapeCounter++;
  58888. f += size;
  58889. }
  58890. return this;
  58891. };
  58892. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58893. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58894. var index = 0;
  58895. var idx = 0;
  58896. for (var p = 0; p < this.particles.length; p++) {
  58897. this._particle = this.particles[p];
  58898. this._shape = this._particle._model._shape;
  58899. if (this._particle.rotationQuaternion) {
  58900. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58901. }
  58902. else {
  58903. this._yaw = this._particle.rotation.y;
  58904. this._pitch = this._particle.rotation.x;
  58905. this._roll = this._particle.rotation.z;
  58906. this._quaternionRotationYPR();
  58907. }
  58908. this._quaternionToRotationMatrix();
  58909. this._rotMatrix.invertToRef(this._invertMatrix);
  58910. for (var pt = 0; pt < this._shape.length; pt++) {
  58911. idx = index + pt * 3;
  58912. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58913. this._fixedNormal32[idx] = this._normal.x;
  58914. this._fixedNormal32[idx + 1] = this._normal.y;
  58915. this._fixedNormal32[idx + 2] = this._normal.z;
  58916. }
  58917. index = idx + 3;
  58918. }
  58919. };
  58920. //reset copy
  58921. SolidParticleSystem.prototype._resetCopy = function () {
  58922. this._copy.position.x = 0;
  58923. this._copy.position.y = 0;
  58924. this._copy.position.z = 0;
  58925. this._copy.rotation.x = 0;
  58926. this._copy.rotation.y = 0;
  58927. this._copy.rotation.z = 0;
  58928. this._copy.rotationQuaternion = null;
  58929. this._copy.scaling.x = 1.0;
  58930. this._copy.scaling.y = 1.0;
  58931. this._copy.scaling.z = 1.0;
  58932. this._copy.uvs.x = 0;
  58933. this._copy.uvs.y = 0;
  58934. this._copy.uvs.z = 1.0;
  58935. this._copy.uvs.w = 1.0;
  58936. this._copy.color = null;
  58937. this._copy.translateFromPivot = false;
  58938. };
  58939. // _meshBuilder : inserts the shape model in the global SPS mesh
  58940. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58941. var i;
  58942. var u = 0;
  58943. var c = 0;
  58944. var n = 0;
  58945. this._resetCopy();
  58946. if (options && options.positionFunction) { // call to custom positionFunction
  58947. options.positionFunction(this._copy, idx, idxInShape);
  58948. this._mustUnrotateFixedNormals = true;
  58949. }
  58950. if (this._copy.rotationQuaternion) {
  58951. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58952. }
  58953. else {
  58954. this._yaw = this._copy.rotation.y;
  58955. this._pitch = this._copy.rotation.x;
  58956. this._roll = this._copy.rotation.z;
  58957. this._quaternionRotationYPR();
  58958. }
  58959. this._quaternionToRotationMatrix();
  58960. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58961. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58962. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58963. if (this._copy.translateFromPivot) {
  58964. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58965. }
  58966. else {
  58967. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58968. }
  58969. for (i = 0; i < shape.length; i++) {
  58970. this._vertex.x = shape[i].x;
  58971. this._vertex.y = shape[i].y;
  58972. this._vertex.z = shape[i].z;
  58973. if (options && options.vertexFunction) {
  58974. options.vertexFunction(this._copy, this._vertex, i);
  58975. }
  58976. this._vertex.x *= this._copy.scaling.x;
  58977. this._vertex.y *= this._copy.scaling.y;
  58978. this._vertex.z *= this._copy.scaling.z;
  58979. this._vertex.x -= this._scaledPivot.x;
  58980. this._vertex.y -= this._scaledPivot.y;
  58981. this._vertex.z -= this._scaledPivot.z;
  58982. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58983. this._rotated.addInPlace(this._pivotBackTranslation);
  58984. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58985. if (meshUV) {
  58986. 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);
  58987. u += 2;
  58988. }
  58989. if (this._copy.color) {
  58990. this._color = this._copy.color;
  58991. }
  58992. else if (meshCol && meshCol[c] !== undefined) {
  58993. this._color.r = meshCol[c];
  58994. this._color.g = meshCol[c + 1];
  58995. this._color.b = meshCol[c + 2];
  58996. this._color.a = meshCol[c + 3];
  58997. }
  58998. else {
  58999. this._color.r = 1.0;
  59000. this._color.g = 1.0;
  59001. this._color.b = 1.0;
  59002. this._color.a = 1.0;
  59003. }
  59004. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  59005. c += 4;
  59006. if (!this.recomputeNormals && meshNor) {
  59007. this._normal.x = meshNor[n];
  59008. this._normal.y = meshNor[n + 1];
  59009. this._normal.z = meshNor[n + 2];
  59010. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  59011. normals.push(this._normal.x, this._normal.y, this._normal.z);
  59012. n += 3;
  59013. }
  59014. }
  59015. for (i = 0; i < meshInd.length; i++) {
  59016. var current_ind = p + meshInd[i];
  59017. indices.push(current_ind);
  59018. if (current_ind > 65535) {
  59019. this._needs32Bits = true;
  59020. }
  59021. }
  59022. if (this._pickable) {
  59023. var nbfaces = meshInd.length / 3;
  59024. for (i = 0; i < nbfaces; i++) {
  59025. this.pickedParticles.push({ idx: idx, faceId: i });
  59026. }
  59027. }
  59028. if (this._depthSort) {
  59029. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  59030. }
  59031. return this._copy;
  59032. };
  59033. // returns a shape array from positions array
  59034. SolidParticleSystem.prototype._posToShape = function (positions) {
  59035. var shape = [];
  59036. for (var i = 0; i < positions.length; i += 3) {
  59037. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  59038. }
  59039. return shape;
  59040. };
  59041. // returns a shapeUV array from a Vector4 uvs
  59042. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  59043. var shapeUV = [];
  59044. if (uvs) {
  59045. for (var i = 0; i < uvs.length; i++)
  59046. shapeUV.push(uvs[i]);
  59047. }
  59048. return shapeUV;
  59049. };
  59050. // adds a new particle object in the particles array
  59051. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  59052. if (bInfo === void 0) { bInfo = null; }
  59053. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  59054. this.particles.push(sp);
  59055. return sp;
  59056. };
  59057. /**
  59058. * Adds some particles to the SPS from the model shape. Returns the shape id.
  59059. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  59060. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  59061. * @param nb (positive integer) the number of particles to be created from this model
  59062. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  59063. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  59064. * @returns the number of shapes in the system
  59065. */
  59066. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  59067. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59068. var meshInd = mesh.getIndices();
  59069. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59070. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59071. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59072. var bbInfo;
  59073. if (this._particlesIntersect) {
  59074. bbInfo = mesh.getBoundingInfo();
  59075. }
  59076. var shape = this._posToShape(meshPos);
  59077. var shapeUV = this._uvsToShapeUV(meshUV);
  59078. var posfunc = options ? options.positionFunction : null;
  59079. var vtxfunc = options ? options.vertexFunction : null;
  59080. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  59081. // particles
  59082. var sp;
  59083. var currentCopy;
  59084. var idx = this.nbParticles;
  59085. for (var i = 0; i < nb; i++) {
  59086. var currentPos = this._positions.length;
  59087. var currentInd = this._indices.length;
  59088. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  59089. if (this._updatable) {
  59090. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  59091. sp.position.copyFrom(currentCopy.position);
  59092. sp.rotation.copyFrom(currentCopy.rotation);
  59093. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  59094. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  59095. }
  59096. if (currentCopy.color && sp.color) {
  59097. sp.color.copyFrom(currentCopy.color);
  59098. }
  59099. sp.scaling.copyFrom(currentCopy.scaling);
  59100. sp.uvs.copyFrom(currentCopy.uvs);
  59101. }
  59102. this._index += shape.length;
  59103. idx++;
  59104. }
  59105. this.nbParticles += nb;
  59106. this._shapeCounter++;
  59107. return this._shapeCounter - 1;
  59108. };
  59109. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59110. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59111. this._resetCopy();
  59112. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59113. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59114. }
  59115. if (this._copy.rotationQuaternion) {
  59116. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59117. }
  59118. else {
  59119. this._yaw = this._copy.rotation.y;
  59120. this._pitch = this._copy.rotation.x;
  59121. this._roll = this._copy.rotation.z;
  59122. this._quaternionRotationYPR();
  59123. }
  59124. this._quaternionToRotationMatrix();
  59125. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59126. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59127. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59128. if (this._copy.translateFromPivot) {
  59129. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59130. }
  59131. else {
  59132. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59133. }
  59134. this._shape = particle._model._shape;
  59135. for (var pt = 0; pt < this._shape.length; pt++) {
  59136. this._vertex.x = this._shape[pt].x;
  59137. this._vertex.y = this._shape[pt].y;
  59138. this._vertex.z = this._shape[pt].z;
  59139. if (particle._model._vertexFunction) {
  59140. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59141. }
  59142. this._vertex.x *= this._copy.scaling.x;
  59143. this._vertex.y *= this._copy.scaling.y;
  59144. this._vertex.z *= this._copy.scaling.z;
  59145. this._vertex.x -= this._scaledPivot.x;
  59146. this._vertex.y -= this._scaledPivot.y;
  59147. this._vertex.z -= this._scaledPivot.z;
  59148. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59149. this._rotated.addInPlace(this._pivotBackTranslation);
  59150. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59151. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59152. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59153. }
  59154. particle.position.x = 0.0;
  59155. particle.position.y = 0.0;
  59156. particle.position.z = 0.0;
  59157. particle.rotation.x = 0.0;
  59158. particle.rotation.y = 0.0;
  59159. particle.rotation.z = 0.0;
  59160. particle.rotationQuaternion = null;
  59161. particle.scaling.x = 1.0;
  59162. particle.scaling.y = 1.0;
  59163. particle.scaling.z = 1.0;
  59164. particle.uvs.x = 0.0;
  59165. particle.uvs.y = 0.0;
  59166. particle.uvs.z = 1.0;
  59167. particle.uvs.w = 1.0;
  59168. particle.pivot.x = 0.0;
  59169. particle.pivot.y = 0.0;
  59170. particle.pivot.z = 0.0;
  59171. particle.translateFromPivot = false;
  59172. particle.parentId = null;
  59173. };
  59174. /**
  59175. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59176. * @returns the SPS.
  59177. */
  59178. SolidParticleSystem.prototype.rebuildMesh = function () {
  59179. for (var p = 0; p < this.particles.length; p++) {
  59180. this._rebuildParticle(this.particles[p]);
  59181. }
  59182. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59183. return this;
  59184. };
  59185. /**
  59186. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59187. * This method calls `updateParticle()` for each particle of the SPS.
  59188. * For an animated SPS, it is usually called within the render loop.
  59189. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59190. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59191. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59192. * @returns the SPS.
  59193. */
  59194. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59195. if (start === void 0) { start = 0; }
  59196. if (end === void 0) { end = this.nbParticles - 1; }
  59197. if (update === void 0) { update = true; }
  59198. if (!this._updatable) {
  59199. return this;
  59200. }
  59201. // custom beforeUpdate
  59202. this.beforeUpdateParticles(start, end, update);
  59203. this._cam_axisX.x = 1.0;
  59204. this._cam_axisX.y = 0.0;
  59205. this._cam_axisX.z = 0.0;
  59206. this._cam_axisY.x = 0.0;
  59207. this._cam_axisY.y = 1.0;
  59208. this._cam_axisY.z = 0.0;
  59209. this._cam_axisZ.x = 0.0;
  59210. this._cam_axisZ.y = 0.0;
  59211. this._cam_axisZ.z = 1.0;
  59212. // cases when the World Matrix is to be computed first
  59213. if (this.billboard || this._depthSort) {
  59214. this.mesh.computeWorldMatrix(true);
  59215. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59216. }
  59217. // if the particles will always face the camera
  59218. if (this.billboard) {
  59219. // compute the camera position and un-rotate it by the current mesh rotation
  59220. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59221. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59222. this._cam_axisZ.normalize();
  59223. // same for camera up vector extracted from the cam view matrix
  59224. var view = this._camera.getViewMatrix(true);
  59225. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59226. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59227. this._cam_axisY.normalize();
  59228. this._cam_axisX.normalize();
  59229. }
  59230. // if depthSort, compute the camera global position in the mesh local system
  59231. if (this._depthSort) {
  59232. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59233. }
  59234. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59235. var idx = 0; // current position index in the global array positions32
  59236. var index = 0; // position start index in the global array positions32 of the current particle
  59237. var colidx = 0; // current color index in the global array colors32
  59238. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59239. var uvidx = 0; // current uv index in the global array uvs32
  59240. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59241. var pt = 0; // current index in the particle model shape
  59242. if (this.mesh.isFacetDataEnabled) {
  59243. this._computeBoundingBox = true;
  59244. }
  59245. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59246. if (this._computeBoundingBox) {
  59247. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59248. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59249. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59250. }
  59251. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59252. if (this.mesh._boundingInfo) {
  59253. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59254. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59255. }
  59256. }
  59257. }
  59258. // particle loop
  59259. index = this.particles[start]._pos;
  59260. var vpos = (index / 3) | 0;
  59261. colorIndex = vpos * 4;
  59262. uvIndex = vpos * 2;
  59263. for (var p = start; p <= end; p++) {
  59264. this._particle = this.particles[p];
  59265. this._shape = this._particle._model._shape;
  59266. this._shapeUV = this._particle._model._shapeUV;
  59267. // call to custom user function to update the particle properties
  59268. this.updateParticle(this._particle);
  59269. // camera-particle distance for depth sorting
  59270. if (this._depthSort && this._depthSortParticles) {
  59271. var dsp = this.depthSortedParticles[p];
  59272. dsp.ind = this._particle._ind;
  59273. dsp.indicesLength = this._particle._model._indicesLength;
  59274. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59275. }
  59276. // skip the computations for inactive or already invisible particles
  59277. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59278. // increment indexes for the next particle
  59279. pt = this._shape.length;
  59280. index += pt * 3;
  59281. colorIndex += pt * 4;
  59282. uvIndex += pt * 2;
  59283. continue;
  59284. }
  59285. if (this._particle.isVisible) {
  59286. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59287. this._particleHasParent = (this._particle.parentId !== null);
  59288. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59289. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59290. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59291. // particle rotation matrix
  59292. if (this.billboard) {
  59293. this._particle.rotation.x = 0.0;
  59294. this._particle.rotation.y = 0.0;
  59295. }
  59296. if (this._computeParticleRotation || this.billboard) {
  59297. if (this._particle.rotationQuaternion) {
  59298. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59299. }
  59300. else {
  59301. this._yaw = this._particle.rotation.y;
  59302. this._pitch = this._particle.rotation.x;
  59303. this._roll = this._particle.rotation.z;
  59304. this._quaternionRotationYPR();
  59305. }
  59306. this._quaternionToRotationMatrix();
  59307. }
  59308. if (this._particleHasParent) {
  59309. this._parent = this.particles[this._particle.parentId];
  59310. 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];
  59311. 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];
  59312. 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];
  59313. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59314. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59315. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59316. if (this._computeParticleRotation || this.billboard) {
  59317. 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];
  59318. 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];
  59319. 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];
  59320. 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];
  59321. 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];
  59322. 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];
  59323. 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];
  59324. 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];
  59325. 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];
  59326. }
  59327. }
  59328. else {
  59329. this._particle._globalPosition.x = this._particle.position.x;
  59330. this._particle._globalPosition.y = this._particle.position.y;
  59331. this._particle._globalPosition.z = this._particle.position.z;
  59332. if (this._computeParticleRotation || this.billboard) {
  59333. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59334. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59335. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59336. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59337. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59338. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59339. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59340. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59341. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59342. }
  59343. }
  59344. if (this._particle.translateFromPivot) {
  59345. this._pivotBackTranslation.x = 0.0;
  59346. this._pivotBackTranslation.y = 0.0;
  59347. this._pivotBackTranslation.z = 0.0;
  59348. }
  59349. else {
  59350. this._pivotBackTranslation.x = this._scaledPivot.x;
  59351. this._pivotBackTranslation.y = this._scaledPivot.y;
  59352. this._pivotBackTranslation.z = this._scaledPivot.z;
  59353. }
  59354. // particle vertex loop
  59355. for (pt = 0; pt < this._shape.length; pt++) {
  59356. idx = index + pt * 3;
  59357. colidx = colorIndex + pt * 4;
  59358. uvidx = uvIndex + pt * 2;
  59359. this._vertex.x = this._shape[pt].x;
  59360. this._vertex.y = this._shape[pt].y;
  59361. this._vertex.z = this._shape[pt].z;
  59362. if (this._computeParticleVertex) {
  59363. this.updateParticleVertex(this._particle, this._vertex, pt);
  59364. }
  59365. // positions
  59366. this._vertex.x *= this._particle.scaling.x;
  59367. this._vertex.y *= this._particle.scaling.y;
  59368. this._vertex.z *= this._particle.scaling.z;
  59369. this._vertex.x -= this._scaledPivot.x;
  59370. this._vertex.y -= this._scaledPivot.y;
  59371. this._vertex.z -= this._scaledPivot.z;
  59372. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59373. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59374. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59375. this._rotated.x += this._pivotBackTranslation.x;
  59376. this._rotated.y += this._pivotBackTranslation.y;
  59377. this._rotated.z += this._pivotBackTranslation.z;
  59378. 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;
  59379. 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;
  59380. 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;
  59381. if (this._computeBoundingBox) {
  59382. if (this._positions32[idx] < this._minimum.x) {
  59383. this._minimum.x = this._positions32[idx];
  59384. }
  59385. if (this._positions32[idx] > this._maximum.x) {
  59386. this._maximum.x = this._positions32[idx];
  59387. }
  59388. if (this._positions32[idx + 1] < this._minimum.y) {
  59389. this._minimum.y = this._positions32[idx + 1];
  59390. }
  59391. if (this._positions32[idx + 1] > this._maximum.y) {
  59392. this._maximum.y = this._positions32[idx + 1];
  59393. }
  59394. if (this._positions32[idx + 2] < this._minimum.z) {
  59395. this._minimum.z = this._positions32[idx + 2];
  59396. }
  59397. if (this._positions32[idx + 2] > this._maximum.z) {
  59398. this._maximum.z = this._positions32[idx + 2];
  59399. }
  59400. }
  59401. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59402. if (!this._computeParticleVertex) {
  59403. this._normal.x = this._fixedNormal32[idx];
  59404. this._normal.y = this._fixedNormal32[idx + 1];
  59405. this._normal.z = this._fixedNormal32[idx + 2];
  59406. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59407. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59408. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59409. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59410. 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;
  59411. 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;
  59412. }
  59413. if (this._computeParticleColor && this._particle.color) {
  59414. this._colors32[colidx] = this._particle.color.r;
  59415. this._colors32[colidx + 1] = this._particle.color.g;
  59416. this._colors32[colidx + 2] = this._particle.color.b;
  59417. this._colors32[colidx + 3] = this._particle.color.a;
  59418. }
  59419. if (this._computeParticleTexture) {
  59420. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59421. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59422. }
  59423. }
  59424. }
  59425. // particle just set invisible : scaled to zero and positioned at the origin
  59426. else {
  59427. this._particle._stillInvisible = true; // mark the particle as invisible
  59428. for (pt = 0; pt < this._shape.length; pt++) {
  59429. idx = index + pt * 3;
  59430. colidx = colorIndex + pt * 4;
  59431. uvidx = uvIndex + pt * 2;
  59432. this._positions32[idx] = 0.0;
  59433. this._positions32[idx + 1] = 0.0;
  59434. this._positions32[idx + 2] = 0.0;
  59435. this._normals32[idx] = 0.0;
  59436. this._normals32[idx + 1] = 0.0;
  59437. this._normals32[idx + 2] = 0.0;
  59438. if (this._computeParticleColor && this._particle.color) {
  59439. this._colors32[colidx] = this._particle.color.r;
  59440. this._colors32[colidx + 1] = this._particle.color.g;
  59441. this._colors32[colidx + 2] = this._particle.color.b;
  59442. this._colors32[colidx + 3] = this._particle.color.a;
  59443. }
  59444. if (this._computeParticleTexture) {
  59445. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59446. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59447. }
  59448. }
  59449. }
  59450. // if the particle intersections must be computed : update the bbInfo
  59451. if (this._particlesIntersect) {
  59452. var bInfo = this._particle._boundingInfo;
  59453. var bBox = bInfo.boundingBox;
  59454. var bSphere = bInfo.boundingSphere;
  59455. if (!this._bSphereOnly) {
  59456. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59457. for (var b = 0; b < bBox.vectors.length; b++) {
  59458. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59459. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59460. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59461. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59462. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59463. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59464. 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;
  59465. 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;
  59466. 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;
  59467. }
  59468. bBox._update(this.mesh._worldMatrix);
  59469. }
  59470. // place and scale the particle bouding sphere in the SPS local system, then update it
  59471. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59472. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59473. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59474. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59475. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59476. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59477. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59478. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59479. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59480. 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));
  59481. bSphere._update(this.mesh._worldMatrix);
  59482. }
  59483. // increment indexes for the next particle
  59484. index = idx + 3;
  59485. colorIndex = colidx + 4;
  59486. uvIndex = uvidx + 2;
  59487. }
  59488. // if the VBO must be updated
  59489. if (update) {
  59490. if (this._computeParticleColor) {
  59491. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59492. }
  59493. if (this._computeParticleTexture) {
  59494. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59495. }
  59496. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59497. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59498. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59499. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59500. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59501. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59502. for (var i = 0; i < this._normals32.length; i++) {
  59503. this._fixedNormal32[i] = this._normals32[i];
  59504. }
  59505. }
  59506. if (!this.mesh.areNormalsFrozen) {
  59507. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59508. }
  59509. }
  59510. if (this._depthSort && this._depthSortParticles) {
  59511. this.depthSortedParticles.sort(this._depthSortFunction);
  59512. var dspl = this.depthSortedParticles.length;
  59513. var sorted = 0;
  59514. var lind = 0;
  59515. var sind = 0;
  59516. var sid = 0;
  59517. for (sorted = 0; sorted < dspl; sorted++) {
  59518. lind = this.depthSortedParticles[sorted].indicesLength;
  59519. sind = this.depthSortedParticles[sorted].ind;
  59520. for (var i = 0; i < lind; i++) {
  59521. this._indices32[sid] = this._indices[sind + i];
  59522. sid++;
  59523. }
  59524. }
  59525. this.mesh.updateIndices(this._indices32);
  59526. }
  59527. }
  59528. if (this._computeBoundingBox) {
  59529. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59530. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59531. }
  59532. this.afterUpdateParticles(start, end, update);
  59533. return this;
  59534. };
  59535. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59536. this._halfroll = this._roll * 0.5;
  59537. this._halfpitch = this._pitch * 0.5;
  59538. this._halfyaw = this._yaw * 0.5;
  59539. this._sinRoll = Math.sin(this._halfroll);
  59540. this._cosRoll = Math.cos(this._halfroll);
  59541. this._sinPitch = Math.sin(this._halfpitch);
  59542. this._cosPitch = Math.cos(this._halfpitch);
  59543. this._sinYaw = Math.sin(this._halfyaw);
  59544. this._cosYaw = Math.cos(this._halfyaw);
  59545. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59546. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59547. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59548. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59549. };
  59550. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59551. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59552. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59553. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59554. this._rotMatrix.m[3] = 0;
  59555. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59556. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59557. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59558. this._rotMatrix.m[7] = 0;
  59559. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59560. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59561. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59562. this._rotMatrix.m[11] = 0;
  59563. this._rotMatrix.m[12] = 0;
  59564. this._rotMatrix.m[13] = 0;
  59565. this._rotMatrix.m[14] = 0;
  59566. this._rotMatrix.m[15] = 1.0;
  59567. };
  59568. /**
  59569. * Disposes the SPS.
  59570. */
  59571. SolidParticleSystem.prototype.dispose = function () {
  59572. this.mesh.dispose();
  59573. this.vars = null;
  59574. // drop references to internal big arrays for the GC
  59575. this._positions = null;
  59576. this._indices = null;
  59577. this._normals = null;
  59578. this._uvs = null;
  59579. this._colors = null;
  59580. this._indices32 = null;
  59581. this._positions32 = null;
  59582. this._normals32 = null;
  59583. this._fixedNormal32 = null;
  59584. this._uvs32 = null;
  59585. this._colors32 = null;
  59586. this.pickedParticles = null;
  59587. };
  59588. /**
  59589. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59590. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59591. * @returns the SPS.
  59592. */
  59593. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59594. if (!this._isVisibilityBoxLocked) {
  59595. this.mesh.refreshBoundingInfo();
  59596. }
  59597. return this;
  59598. };
  59599. /**
  59600. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59601. * @param size the size (float) of the visibility box
  59602. * note : this doesn't lock the SPS mesh bounding box.
  59603. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59604. */
  59605. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59606. var vis = size / 2;
  59607. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59608. };
  59609. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59610. /**
  59611. * Gets whether the SPS as always visible or not
  59612. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59613. */
  59614. get: function () {
  59615. return this._alwaysVisible;
  59616. },
  59617. /**
  59618. * Sets the SPS as always visible or not
  59619. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59620. */
  59621. set: function (val) {
  59622. this._alwaysVisible = val;
  59623. this.mesh.alwaysSelectAsActiveMesh = val;
  59624. },
  59625. enumerable: true,
  59626. configurable: true
  59627. });
  59628. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59629. /**
  59630. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59631. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59632. */
  59633. get: function () {
  59634. return this._isVisibilityBoxLocked;
  59635. },
  59636. /**
  59637. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59638. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59639. */
  59640. set: function (val) {
  59641. this._isVisibilityBoxLocked = val;
  59642. var boundingInfo = this.mesh.getBoundingInfo();
  59643. boundingInfo.isLocked = val;
  59644. },
  59645. enumerable: true,
  59646. configurable: true
  59647. });
  59648. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59649. /**
  59650. * Gets if `setParticles()` computes the particle rotations or not.
  59651. * Default value : true. The SPS is faster when it's set to false.
  59652. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59653. */
  59654. get: function () {
  59655. return this._computeParticleRotation;
  59656. },
  59657. /**
  59658. * Tells to `setParticles()` to compute the particle rotations or not.
  59659. * Default value : true. The SPS is faster when it's set to false.
  59660. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59661. */
  59662. set: function (val) {
  59663. this._computeParticleRotation = val;
  59664. },
  59665. enumerable: true,
  59666. configurable: true
  59667. });
  59668. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59669. /**
  59670. * Gets if `setParticles()` computes the particle colors or not.
  59671. * Default value : true. The SPS is faster when it's set to false.
  59672. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59673. */
  59674. get: function () {
  59675. return this._computeParticleColor;
  59676. },
  59677. /**
  59678. * Tells to `setParticles()` to compute the particle colors or not.
  59679. * Default value : true. The SPS is faster when it's set to false.
  59680. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59681. */
  59682. set: function (val) {
  59683. this._computeParticleColor = val;
  59684. },
  59685. enumerable: true,
  59686. configurable: true
  59687. });
  59688. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59689. /**
  59690. * Gets if `setParticles()` computes the particle textures or not.
  59691. * Default value : true. The SPS is faster when it's set to false.
  59692. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59693. */
  59694. get: function () {
  59695. return this._computeParticleTexture;
  59696. },
  59697. set: function (val) {
  59698. this._computeParticleTexture = val;
  59699. },
  59700. enumerable: true,
  59701. configurable: true
  59702. });
  59703. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59704. /**
  59705. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59706. * Default value : false. The SPS is faster when it's set to false.
  59707. * Note : the particle custom vertex positions aren't stored values.
  59708. */
  59709. get: function () {
  59710. return this._computeParticleVertex;
  59711. },
  59712. /**
  59713. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59714. * Default value : false. The SPS is faster when it's set to false.
  59715. * Note : the particle custom vertex positions aren't stored values.
  59716. */
  59717. set: function (val) {
  59718. this._computeParticleVertex = val;
  59719. },
  59720. enumerable: true,
  59721. configurable: true
  59722. });
  59723. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59724. /**
  59725. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59726. */
  59727. get: function () {
  59728. return this._computeBoundingBox;
  59729. },
  59730. /**
  59731. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59732. */
  59733. set: function (val) {
  59734. this._computeBoundingBox = val;
  59735. },
  59736. enumerable: true,
  59737. configurable: true
  59738. });
  59739. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59740. /**
  59741. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59742. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59743. * Default : `true`
  59744. */
  59745. get: function () {
  59746. return this._depthSortParticles;
  59747. },
  59748. /**
  59749. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59750. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59751. * Default : `true`
  59752. */
  59753. set: function (val) {
  59754. this._depthSortParticles = val;
  59755. },
  59756. enumerable: true,
  59757. configurable: true
  59758. });
  59759. // =======================================================================
  59760. // Particle behavior logic
  59761. // these following methods may be overwritten by the user to fit his needs
  59762. /**
  59763. * This function does nothing. It may be overwritten to set all the particle first values.
  59764. * The SPS doesn't call this function, you may have to call it by your own.
  59765. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59766. */
  59767. SolidParticleSystem.prototype.initParticles = function () {
  59768. };
  59769. /**
  59770. * This function does nothing. It may be overwritten to recycle a particle.
  59771. * The SPS doesn't call this function, you may have to call it by your own.
  59772. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59773. * @param particle The particle to recycle
  59774. * @returns the recycled particle
  59775. */
  59776. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59777. return particle;
  59778. };
  59779. /**
  59780. * Updates a particle : this function should be overwritten by the user.
  59781. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59782. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59783. * @example : just set a particle position or velocity and recycle conditions
  59784. * @param particle The particle to update
  59785. * @returns the updated particle
  59786. */
  59787. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59788. return particle;
  59789. };
  59790. /**
  59791. * Updates a vertex of a particle : it can be overwritten by the user.
  59792. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59793. * @param particle the current particle
  59794. * @param vertex the current index of the current particle
  59795. * @param pt the index of the current vertex in the particle shape
  59796. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59797. * @example : just set a vertex particle position
  59798. * @returns the updated vertex
  59799. */
  59800. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59801. return vertex;
  59802. };
  59803. /**
  59804. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59805. * This does nothing and may be overwritten by the user.
  59806. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59807. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59808. * @param update the boolean update value actually passed to setParticles()
  59809. */
  59810. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59811. };
  59812. /**
  59813. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59814. * This will be passed three parameters.
  59815. * This does nothing and may be overwritten by the user.
  59816. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59817. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59818. * @param update the boolean update value actually passed to setParticles()
  59819. */
  59820. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59821. };
  59822. return SolidParticleSystem;
  59823. }());
  59824. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59825. })(BABYLON || (BABYLON = {}));
  59826. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59827. var BABYLON;
  59828. (function (BABYLON) {
  59829. var ShaderMaterial = /** @class */ (function (_super) {
  59830. __extends(ShaderMaterial, _super);
  59831. function ShaderMaterial(name, scene, shaderPath, options) {
  59832. var _this = _super.call(this, name, scene) || this;
  59833. _this._textures = {};
  59834. _this._textureArrays = {};
  59835. _this._floats = {};
  59836. _this._ints = {};
  59837. _this._floatsArrays = {};
  59838. _this._colors3 = {};
  59839. _this._colors3Arrays = {};
  59840. _this._colors4 = {};
  59841. _this._vectors2 = {};
  59842. _this._vectors3 = {};
  59843. _this._vectors4 = {};
  59844. _this._matrices = {};
  59845. _this._matrices3x3 = {};
  59846. _this._matrices2x2 = {};
  59847. _this._vectors2Arrays = {};
  59848. _this._vectors3Arrays = {};
  59849. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59850. _this._shaderPath = shaderPath;
  59851. options.needAlphaBlending = options.needAlphaBlending || false;
  59852. options.needAlphaTesting = options.needAlphaTesting || false;
  59853. options.attributes = options.attributes || ["position", "normal", "uv"];
  59854. options.uniforms = options.uniforms || ["worldViewProjection"];
  59855. options.uniformBuffers = options.uniformBuffers || [];
  59856. options.samplers = options.samplers || [];
  59857. options.defines = options.defines || [];
  59858. _this._options = options;
  59859. return _this;
  59860. }
  59861. ShaderMaterial.prototype.getClassName = function () {
  59862. return "ShaderMaterial";
  59863. };
  59864. ShaderMaterial.prototype.needAlphaBlending = function () {
  59865. return this._options.needAlphaBlending;
  59866. };
  59867. ShaderMaterial.prototype.needAlphaTesting = function () {
  59868. return this._options.needAlphaTesting;
  59869. };
  59870. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59871. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59872. this._options.uniforms.push(uniformName);
  59873. }
  59874. };
  59875. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59876. if (this._options.samplers.indexOf(name) === -1) {
  59877. this._options.samplers.push(name);
  59878. }
  59879. this._textures[name] = texture;
  59880. return this;
  59881. };
  59882. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59883. if (this._options.samplers.indexOf(name) === -1) {
  59884. this._options.samplers.push(name);
  59885. }
  59886. this._checkUniform(name);
  59887. this._textureArrays[name] = textures;
  59888. return this;
  59889. };
  59890. ShaderMaterial.prototype.setFloat = function (name, value) {
  59891. this._checkUniform(name);
  59892. this._floats[name] = value;
  59893. return this;
  59894. };
  59895. ShaderMaterial.prototype.setInt = function (name, value) {
  59896. this._checkUniform(name);
  59897. this._ints[name] = value;
  59898. return this;
  59899. };
  59900. ShaderMaterial.prototype.setFloats = function (name, value) {
  59901. this._checkUniform(name);
  59902. this._floatsArrays[name] = value;
  59903. return this;
  59904. };
  59905. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59906. this._checkUniform(name);
  59907. this._colors3[name] = value;
  59908. return this;
  59909. };
  59910. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59911. this._checkUniform(name);
  59912. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59913. color.toArray(arr, arr.length);
  59914. return arr;
  59915. }, []);
  59916. return this;
  59917. };
  59918. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59919. this._checkUniform(name);
  59920. this._colors4[name] = value;
  59921. return this;
  59922. };
  59923. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59924. this._checkUniform(name);
  59925. this._vectors2[name] = value;
  59926. return this;
  59927. };
  59928. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59929. this._checkUniform(name);
  59930. this._vectors3[name] = value;
  59931. return this;
  59932. };
  59933. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59934. this._checkUniform(name);
  59935. this._vectors4[name] = value;
  59936. return this;
  59937. };
  59938. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59939. this._checkUniform(name);
  59940. this._matrices[name] = value;
  59941. return this;
  59942. };
  59943. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59944. this._checkUniform(name);
  59945. this._matrices3x3[name] = value;
  59946. return this;
  59947. };
  59948. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59949. this._checkUniform(name);
  59950. this._matrices2x2[name] = value;
  59951. return this;
  59952. };
  59953. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59954. this._checkUniform(name);
  59955. this._vectors2Arrays[name] = value;
  59956. return this;
  59957. };
  59958. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59959. this._checkUniform(name);
  59960. this._vectors3Arrays[name] = value;
  59961. return this;
  59962. };
  59963. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59964. if (!mesh) {
  59965. return true;
  59966. }
  59967. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59968. return false;
  59969. }
  59970. return false;
  59971. };
  59972. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59973. var scene = this.getScene();
  59974. var engine = scene.getEngine();
  59975. if (!this.checkReadyOnEveryCall) {
  59976. if (this._renderId === scene.getRenderId()) {
  59977. if (this._checkCache(scene, mesh, useInstances)) {
  59978. return true;
  59979. }
  59980. }
  59981. }
  59982. // Instances
  59983. var defines = [];
  59984. var attribs = [];
  59985. var fallbacks = new BABYLON.EffectFallbacks();
  59986. if (useInstances) {
  59987. defines.push("#define INSTANCES");
  59988. }
  59989. for (var index = 0; index < this._options.defines.length; index++) {
  59990. defines.push(this._options.defines[index]);
  59991. }
  59992. for (var index = 0; index < this._options.attributes.length; index++) {
  59993. attribs.push(this._options.attributes[index]);
  59994. }
  59995. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59996. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59997. defines.push("#define VERTEXCOLOR");
  59998. }
  59999. // Bones
  60000. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60003. if (mesh.numBoneInfluencers > 4) {
  60004. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60005. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60006. }
  60007. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60008. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60009. fallbacks.addCPUSkinningFallback(0, mesh);
  60010. if (this._options.uniforms.indexOf("mBones") === -1) {
  60011. this._options.uniforms.push("mBones");
  60012. }
  60013. }
  60014. else {
  60015. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60016. }
  60017. // Textures
  60018. for (var name in this._textures) {
  60019. if (!this._textures[name].isReady()) {
  60020. return false;
  60021. }
  60022. }
  60023. // Alpha test
  60024. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60025. defines.push("#define ALPHATEST");
  60026. }
  60027. var previousEffect = this._effect;
  60028. var join = defines.join("\n");
  60029. this._effect = engine.createEffect(this._shaderPath, {
  60030. attributes: attribs,
  60031. uniformsNames: this._options.uniforms,
  60032. uniformBuffersNames: this._options.uniformBuffers,
  60033. samplers: this._options.samplers,
  60034. defines: join,
  60035. fallbacks: fallbacks,
  60036. onCompiled: this.onCompiled,
  60037. onError: this.onError
  60038. }, engine);
  60039. if (!this._effect.isReady()) {
  60040. return false;
  60041. }
  60042. if (previousEffect !== this._effect) {
  60043. scene.resetCachedMaterial();
  60044. }
  60045. this._renderId = scene.getRenderId();
  60046. return true;
  60047. };
  60048. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60049. var scene = this.getScene();
  60050. if (!this._effect) {
  60051. return;
  60052. }
  60053. if (this._options.uniforms.indexOf("world") !== -1) {
  60054. this._effect.setMatrix("world", world);
  60055. }
  60056. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60057. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60058. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60059. }
  60060. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60061. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60062. }
  60063. };
  60064. ShaderMaterial.prototype.bind = function (world, mesh) {
  60065. // Std values
  60066. this.bindOnlyWorldMatrix(world);
  60067. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60068. if (this._options.uniforms.indexOf("view") !== -1) {
  60069. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60070. }
  60071. if (this._options.uniforms.indexOf("projection") !== -1) {
  60072. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60073. }
  60074. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60075. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60076. }
  60077. // Bones
  60078. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60079. var name;
  60080. // Texture
  60081. for (name in this._textures) {
  60082. this._effect.setTexture(name, this._textures[name]);
  60083. }
  60084. // Texture arrays
  60085. for (name in this._textureArrays) {
  60086. this._effect.setTextureArray(name, this._textureArrays[name]);
  60087. }
  60088. // Int
  60089. for (name in this._ints) {
  60090. this._effect.setInt(name, this._ints[name]);
  60091. }
  60092. // Float
  60093. for (name in this._floats) {
  60094. this._effect.setFloat(name, this._floats[name]);
  60095. }
  60096. // Floats
  60097. for (name in this._floatsArrays) {
  60098. this._effect.setArray(name, this._floatsArrays[name]);
  60099. }
  60100. // Color3
  60101. for (name in this._colors3) {
  60102. this._effect.setColor3(name, this._colors3[name]);
  60103. }
  60104. for (name in this._colors3Arrays) {
  60105. this._effect.setArray3(name, this._colors3Arrays[name]);
  60106. }
  60107. // Color4
  60108. for (name in this._colors4) {
  60109. var color = this._colors4[name];
  60110. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60111. }
  60112. // Vector2
  60113. for (name in this._vectors2) {
  60114. this._effect.setVector2(name, this._vectors2[name]);
  60115. }
  60116. // Vector3
  60117. for (name in this._vectors3) {
  60118. this._effect.setVector3(name, this._vectors3[name]);
  60119. }
  60120. // Vector4
  60121. for (name in this._vectors4) {
  60122. this._effect.setVector4(name, this._vectors4[name]);
  60123. }
  60124. // Matrix
  60125. for (name in this._matrices) {
  60126. this._effect.setMatrix(name, this._matrices[name]);
  60127. }
  60128. // Matrix 3x3
  60129. for (name in this._matrices3x3) {
  60130. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60131. }
  60132. // Matrix 2x2
  60133. for (name in this._matrices2x2) {
  60134. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60135. }
  60136. // Vector2Array
  60137. for (name in this._vectors2Arrays) {
  60138. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60139. }
  60140. // Vector3Array
  60141. for (name in this._vectors3Arrays) {
  60142. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60143. }
  60144. }
  60145. this._afterBind(mesh);
  60146. };
  60147. ShaderMaterial.prototype.getActiveTextures = function () {
  60148. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60149. for (var name in this._textures) {
  60150. activeTextures.push(this._textures[name]);
  60151. }
  60152. for (var name in this._textureArrays) {
  60153. var array = this._textureArrays[name];
  60154. for (var index = 0; index < array.length; index++) {
  60155. activeTextures.push(array[index]);
  60156. }
  60157. }
  60158. return activeTextures;
  60159. };
  60160. ShaderMaterial.prototype.hasTexture = function (texture) {
  60161. if (_super.prototype.hasTexture.call(this, texture)) {
  60162. return true;
  60163. }
  60164. for (var name in this._textures) {
  60165. if (this._textures[name] === texture) {
  60166. return true;
  60167. }
  60168. }
  60169. for (var name in this._textureArrays) {
  60170. var array = this._textureArrays[name];
  60171. for (var index = 0; index < array.length; index++) {
  60172. if (array[index] === texture) {
  60173. return true;
  60174. }
  60175. }
  60176. }
  60177. return false;
  60178. };
  60179. ShaderMaterial.prototype.clone = function (name) {
  60180. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60181. return newShaderMaterial;
  60182. };
  60183. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60184. if (forceDisposeTextures) {
  60185. var name;
  60186. for (name in this._textures) {
  60187. this._textures[name].dispose();
  60188. }
  60189. for (name in this._textureArrays) {
  60190. var array = this._textureArrays[name];
  60191. for (var index = 0; index < array.length; index++) {
  60192. array[index].dispose();
  60193. }
  60194. }
  60195. }
  60196. this._textures = {};
  60197. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60198. };
  60199. ShaderMaterial.prototype.serialize = function () {
  60200. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60201. serializationObject.customType = "BABYLON.ShaderMaterial";
  60202. serializationObject.options = this._options;
  60203. serializationObject.shaderPath = this._shaderPath;
  60204. var name;
  60205. // Texture
  60206. serializationObject.textures = {};
  60207. for (name in this._textures) {
  60208. serializationObject.textures[name] = this._textures[name].serialize();
  60209. }
  60210. // Texture arrays
  60211. serializationObject.textureArrays = {};
  60212. for (name in this._textureArrays) {
  60213. serializationObject.textureArrays[name] = [];
  60214. var array = this._textureArrays[name];
  60215. for (var index = 0; index < array.length; index++) {
  60216. serializationObject.textureArrays[name].push(array[index].serialize());
  60217. }
  60218. }
  60219. // Float
  60220. serializationObject.floats = {};
  60221. for (name in this._floats) {
  60222. serializationObject.floats[name] = this._floats[name];
  60223. }
  60224. // Float s
  60225. serializationObject.FloatArrays = {};
  60226. for (name in this._floatsArrays) {
  60227. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60228. }
  60229. // Color3
  60230. serializationObject.colors3 = {};
  60231. for (name in this._colors3) {
  60232. serializationObject.colors3[name] = this._colors3[name].asArray();
  60233. }
  60234. // Color3 array
  60235. serializationObject.colors3Arrays = {};
  60236. for (name in this._colors3Arrays) {
  60237. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60238. }
  60239. // Color4
  60240. serializationObject.colors4 = {};
  60241. for (name in this._colors4) {
  60242. serializationObject.colors4[name] = this._colors4[name].asArray();
  60243. }
  60244. // Vector2
  60245. serializationObject.vectors2 = {};
  60246. for (name in this._vectors2) {
  60247. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60248. }
  60249. // Vector3
  60250. serializationObject.vectors3 = {};
  60251. for (name in this._vectors3) {
  60252. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60253. }
  60254. // Vector4
  60255. serializationObject.vectors4 = {};
  60256. for (name in this._vectors4) {
  60257. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60258. }
  60259. // Matrix
  60260. serializationObject.matrices = {};
  60261. for (name in this._matrices) {
  60262. serializationObject.matrices[name] = this._matrices[name].asArray();
  60263. }
  60264. // Matrix 3x3
  60265. serializationObject.matrices3x3 = {};
  60266. for (name in this._matrices3x3) {
  60267. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60268. }
  60269. // Matrix 2x2
  60270. serializationObject.matrices2x2 = {};
  60271. for (name in this._matrices2x2) {
  60272. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60273. }
  60274. // Vector2Array
  60275. serializationObject.vectors2Arrays = {};
  60276. for (name in this._vectors2Arrays) {
  60277. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60278. }
  60279. // Vector3Array
  60280. serializationObject.vectors3Arrays = {};
  60281. for (name in this._vectors3Arrays) {
  60282. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60283. }
  60284. return serializationObject;
  60285. };
  60286. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60287. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60288. var name;
  60289. // Texture
  60290. for (name in source.textures) {
  60291. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60292. }
  60293. // Texture arrays
  60294. for (name in source.textureArrays) {
  60295. var array = source.textureArrays[name];
  60296. var textureArray = new Array();
  60297. for (var index = 0; index < array.length; index++) {
  60298. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60299. }
  60300. material.setTextureArray(name, textureArray);
  60301. }
  60302. // Float
  60303. for (name in source.floats) {
  60304. material.setFloat(name, source.floats[name]);
  60305. }
  60306. // Float s
  60307. for (name in source.floatsArrays) {
  60308. material.setFloats(name, source.floatsArrays[name]);
  60309. }
  60310. // Color3
  60311. for (name in source.colors3) {
  60312. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60313. }
  60314. // Color3 arrays
  60315. for (name in source.colors3Arrays) {
  60316. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60317. if (i % 3 === 0) {
  60318. arr.push([num]);
  60319. }
  60320. else {
  60321. arr[arr.length - 1].push(num);
  60322. }
  60323. return arr;
  60324. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60325. material.setColor3Array(name, colors);
  60326. }
  60327. // Color4
  60328. for (name in source.colors4) {
  60329. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60330. }
  60331. // Vector2
  60332. for (name in source.vectors2) {
  60333. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60334. }
  60335. // Vector3
  60336. for (name in source.vectors3) {
  60337. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60338. }
  60339. // Vector4
  60340. for (name in source.vectors4) {
  60341. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60342. }
  60343. // Matrix
  60344. for (name in source.matrices) {
  60345. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60346. }
  60347. // Matrix 3x3
  60348. for (name in source.matrices3x3) {
  60349. material.setMatrix3x3(name, source.matrices3x3[name]);
  60350. }
  60351. // Matrix 2x2
  60352. for (name in source.matrices2x2) {
  60353. material.setMatrix2x2(name, source.matrices2x2[name]);
  60354. }
  60355. // Vector2Array
  60356. for (name in source.vectors2Arrays) {
  60357. material.setArray2(name, source.vectors2Arrays[name]);
  60358. }
  60359. // Vector3Array
  60360. for (name in source.vectors3Arrays) {
  60361. material.setArray3(name, source.vectors3Arrays[name]);
  60362. }
  60363. return material;
  60364. };
  60365. return ShaderMaterial;
  60366. }(BABYLON.Material));
  60367. BABYLON.ShaderMaterial = ShaderMaterial;
  60368. })(BABYLON || (BABYLON = {}));
  60369. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60370. var BABYLON;
  60371. (function (BABYLON) {
  60372. var GroundMesh = /** @class */ (function (_super) {
  60373. __extends(GroundMesh, _super);
  60374. function GroundMesh(name, scene) {
  60375. var _this = _super.call(this, name, scene) || this;
  60376. _this.generateOctree = false;
  60377. return _this;
  60378. }
  60379. GroundMesh.prototype.getClassName = function () {
  60380. return "GroundMesh";
  60381. };
  60382. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60383. get: function () {
  60384. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60385. },
  60386. enumerable: true,
  60387. configurable: true
  60388. });
  60389. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60390. get: function () {
  60391. return this._subdivisionsX;
  60392. },
  60393. enumerable: true,
  60394. configurable: true
  60395. });
  60396. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60397. get: function () {
  60398. return this._subdivisionsY;
  60399. },
  60400. enumerable: true,
  60401. configurable: true
  60402. });
  60403. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60404. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60405. this._subdivisionsX = chunksCount;
  60406. this._subdivisionsY = chunksCount;
  60407. this.subdivide(chunksCount);
  60408. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60409. };
  60410. /**
  60411. * Returns a height (y) value in the Worl system :
  60412. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60413. * Returns the ground y position if (x, z) are outside the ground surface.
  60414. */
  60415. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60416. var world = this.getWorldMatrix();
  60417. var invMat = BABYLON.Tmp.Matrix[5];
  60418. world.invertToRef(invMat);
  60419. var tmpVect = BABYLON.Tmp.Vector3[8];
  60420. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60421. x = tmpVect.x;
  60422. z = tmpVect.z;
  60423. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60424. return this.position.y;
  60425. }
  60426. if (!this._heightQuads || this._heightQuads.length == 0) {
  60427. this._initHeightQuads();
  60428. this._computeHeightQuads();
  60429. }
  60430. var facet = this._getFacetAt(x, z);
  60431. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60432. // return y in the World system
  60433. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60434. return tmpVect.y;
  60435. };
  60436. /**
  60437. * Returns a normalized vector (Vector3) orthogonal to the ground
  60438. * at the ground coordinates (x, z) expressed in the World system.
  60439. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60440. */
  60441. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60442. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60443. this.getNormalAtCoordinatesToRef(x, z, normal);
  60444. return normal;
  60445. };
  60446. /**
  60447. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60448. * at the ground coordinates (x, z) expressed in the World system.
  60449. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60450. * Returns the GroundMesh.
  60451. */
  60452. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60453. var world = this.getWorldMatrix();
  60454. var tmpMat = BABYLON.Tmp.Matrix[5];
  60455. world.invertToRef(tmpMat);
  60456. var tmpVect = BABYLON.Tmp.Vector3[8];
  60457. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60458. x = tmpVect.x;
  60459. z = tmpVect.z;
  60460. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60461. return this;
  60462. }
  60463. if (!this._heightQuads || this._heightQuads.length == 0) {
  60464. this._initHeightQuads();
  60465. this._computeHeightQuads();
  60466. }
  60467. var facet = this._getFacetAt(x, z);
  60468. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60469. return this;
  60470. };
  60471. /**
  60472. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60473. * if the ground has been updated.
  60474. * This can be used in the render loop.
  60475. * Returns the GroundMesh.
  60476. */
  60477. GroundMesh.prototype.updateCoordinateHeights = function () {
  60478. if (!this._heightQuads || this._heightQuads.length == 0) {
  60479. this._initHeightQuads();
  60480. }
  60481. this._computeHeightQuads();
  60482. return this;
  60483. };
  60484. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60485. GroundMesh.prototype._getFacetAt = function (x, z) {
  60486. // retrieve col and row from x, z coordinates in the ground local system
  60487. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60488. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60489. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60490. var facet;
  60491. if (z < quad.slope.x * x + quad.slope.y) {
  60492. facet = quad.facet1;
  60493. }
  60494. else {
  60495. facet = quad.facet2;
  60496. }
  60497. return facet;
  60498. };
  60499. // Creates and populates the heightMap array with "facet" elements :
  60500. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60501. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60502. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60503. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60504. // Returns the GroundMesh.
  60505. GroundMesh.prototype._initHeightQuads = function () {
  60506. var subdivisionsX = this._subdivisionsX;
  60507. var subdivisionsY = this._subdivisionsY;
  60508. this._heightQuads = new Array();
  60509. for (var row = 0; row < subdivisionsY; row++) {
  60510. for (var col = 0; col < subdivisionsX; col++) {
  60511. 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) };
  60512. this._heightQuads[row * subdivisionsX + col] = quad;
  60513. }
  60514. }
  60515. return this;
  60516. };
  60517. // Compute each quad element values and update the the heightMap array :
  60518. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60519. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60520. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60521. // Returns the GroundMesh.
  60522. GroundMesh.prototype._computeHeightQuads = function () {
  60523. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60524. if (!positions) {
  60525. return this;
  60526. }
  60527. var v1 = BABYLON.Tmp.Vector3[3];
  60528. var v2 = BABYLON.Tmp.Vector3[2];
  60529. var v3 = BABYLON.Tmp.Vector3[1];
  60530. var v4 = BABYLON.Tmp.Vector3[0];
  60531. var v1v2 = BABYLON.Tmp.Vector3[4];
  60532. var v1v3 = BABYLON.Tmp.Vector3[5];
  60533. var v1v4 = BABYLON.Tmp.Vector3[6];
  60534. var norm1 = BABYLON.Tmp.Vector3[7];
  60535. var norm2 = BABYLON.Tmp.Vector3[8];
  60536. var i = 0;
  60537. var j = 0;
  60538. var k = 0;
  60539. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60540. var h = 0;
  60541. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60542. var d2 = 0;
  60543. var subdivisionsX = this._subdivisionsX;
  60544. var subdivisionsY = this._subdivisionsY;
  60545. for (var row = 0; row < subdivisionsY; row++) {
  60546. for (var col = 0; col < subdivisionsX; col++) {
  60547. i = col * 3;
  60548. j = row * (subdivisionsX + 1) * 3;
  60549. k = (row + 1) * (subdivisionsX + 1) * 3;
  60550. v1.x = positions[j + i];
  60551. v1.y = positions[j + i + 1];
  60552. v1.z = positions[j + i + 2];
  60553. v2.x = positions[j + i + 3];
  60554. v2.y = positions[j + i + 4];
  60555. v2.z = positions[j + i + 5];
  60556. v3.x = positions[k + i];
  60557. v3.y = positions[k + i + 1];
  60558. v3.z = positions[k + i + 2];
  60559. v4.x = positions[k + i + 3];
  60560. v4.y = positions[k + i + 4];
  60561. v4.z = positions[k + i + 5];
  60562. // 2D slope V1V4
  60563. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60564. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60565. // facet equations :
  60566. // we compute each facet normal vector
  60567. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60568. // we compute the value d by applying the equation to v1 which belongs to the plane
  60569. // then we store the facet equation in a Vector4
  60570. v2.subtractToRef(v1, v1v2);
  60571. v3.subtractToRef(v1, v1v3);
  60572. v4.subtractToRef(v1, v1v4);
  60573. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60574. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60575. norm1.normalize();
  60576. norm2.normalize();
  60577. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60578. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60579. var quad = this._heightQuads[row * subdivisionsX + col];
  60580. quad.slope.copyFromFloats(cd, h);
  60581. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60582. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60583. }
  60584. }
  60585. return this;
  60586. };
  60587. GroundMesh.prototype.serialize = function (serializationObject) {
  60588. _super.prototype.serialize.call(this, serializationObject);
  60589. serializationObject.subdivisionsX = this._subdivisionsX;
  60590. serializationObject.subdivisionsY = this._subdivisionsY;
  60591. serializationObject.minX = this._minX;
  60592. serializationObject.maxX = this._maxX;
  60593. serializationObject.minZ = this._minZ;
  60594. serializationObject.maxZ = this._maxZ;
  60595. serializationObject.width = this._width;
  60596. serializationObject.height = this._height;
  60597. };
  60598. GroundMesh.Parse = function (parsedMesh, scene) {
  60599. var result = new GroundMesh(parsedMesh.name, scene);
  60600. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60601. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60602. result._minX = parsedMesh.minX;
  60603. result._maxX = parsedMesh.maxX;
  60604. result._minZ = parsedMesh.minZ;
  60605. result._maxZ = parsedMesh.maxZ;
  60606. result._width = parsedMesh.width;
  60607. result._height = parsedMesh.height;
  60608. return result;
  60609. };
  60610. return GroundMesh;
  60611. }(BABYLON.Mesh));
  60612. BABYLON.GroundMesh = GroundMesh;
  60613. })(BABYLON || (BABYLON = {}));
  60614. //# sourceMappingURL=babylon.groundMesh.js.map
  60615. var BABYLON;
  60616. (function (BABYLON) {
  60617. /**
  60618. * Creates an instance based on a source mesh.
  60619. */
  60620. var InstancedMesh = /** @class */ (function (_super) {
  60621. __extends(InstancedMesh, _super);
  60622. function InstancedMesh(name, source) {
  60623. var _this = _super.call(this, name, source.getScene()) || this;
  60624. source.instances.push(_this);
  60625. _this._sourceMesh = source;
  60626. _this.position.copyFrom(source.position);
  60627. _this.rotation.copyFrom(source.rotation);
  60628. _this.scaling.copyFrom(source.scaling);
  60629. if (source.rotationQuaternion) {
  60630. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60631. }
  60632. _this.infiniteDistance = source.infiniteDistance;
  60633. _this.setPivotMatrix(source.getPivotMatrix());
  60634. _this.refreshBoundingInfo();
  60635. _this._syncSubMeshes();
  60636. return _this;
  60637. }
  60638. /**
  60639. * Returns the string "InstancedMesh".
  60640. */
  60641. InstancedMesh.prototype.getClassName = function () {
  60642. return "InstancedMesh";
  60643. };
  60644. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60645. // Methods
  60646. get: function () {
  60647. return this._sourceMesh.receiveShadows;
  60648. },
  60649. enumerable: true,
  60650. configurable: true
  60651. });
  60652. Object.defineProperty(InstancedMesh.prototype, "material", {
  60653. get: function () {
  60654. return this._sourceMesh.material;
  60655. },
  60656. enumerable: true,
  60657. configurable: true
  60658. });
  60659. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60660. get: function () {
  60661. return this._sourceMesh.visibility;
  60662. },
  60663. enumerable: true,
  60664. configurable: true
  60665. });
  60666. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60667. get: function () {
  60668. return this._sourceMesh.skeleton;
  60669. },
  60670. enumerable: true,
  60671. configurable: true
  60672. });
  60673. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60674. get: function () {
  60675. return this._sourceMesh.renderingGroupId;
  60676. },
  60677. set: function (value) {
  60678. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60679. return;
  60680. }
  60681. //no-op with warning
  60682. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60683. },
  60684. enumerable: true,
  60685. configurable: true
  60686. });
  60687. /**
  60688. * Returns the total number of vertices (integer).
  60689. */
  60690. InstancedMesh.prototype.getTotalVertices = function () {
  60691. return this._sourceMesh.getTotalVertices();
  60692. };
  60693. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60694. get: function () {
  60695. return this._sourceMesh;
  60696. },
  60697. enumerable: true,
  60698. configurable: true
  60699. });
  60700. /**
  60701. * Is this node ready to be used/rendered
  60702. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60703. * @return {boolean} is it ready
  60704. */
  60705. InstancedMesh.prototype.isReady = function (completeCheck) {
  60706. if (completeCheck === void 0) { completeCheck = false; }
  60707. return this._sourceMesh.isReady(completeCheck, true);
  60708. };
  60709. /**
  60710. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60711. */
  60712. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60713. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60714. };
  60715. /**
  60716. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60717. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60718. * The `data` are either a numeric array either a Float32Array.
  60719. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60720. * 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).
  60721. * Note that a new underlying VertexBuffer object is created each call.
  60722. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60723. *
  60724. * Possible `kind` values :
  60725. * - BABYLON.VertexBuffer.PositionKind
  60726. * - BABYLON.VertexBuffer.UVKind
  60727. * - BABYLON.VertexBuffer.UV2Kind
  60728. * - BABYLON.VertexBuffer.UV3Kind
  60729. * - BABYLON.VertexBuffer.UV4Kind
  60730. * - BABYLON.VertexBuffer.UV5Kind
  60731. * - BABYLON.VertexBuffer.UV6Kind
  60732. * - BABYLON.VertexBuffer.ColorKind
  60733. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60734. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60735. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60736. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60737. *
  60738. * Returns the Mesh.
  60739. */
  60740. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60741. if (this.sourceMesh) {
  60742. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60743. }
  60744. return this.sourceMesh;
  60745. };
  60746. /**
  60747. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60748. * If the mesh has no geometry, it is simply returned as it is.
  60749. * The `data` are either a numeric array either a Float32Array.
  60750. * No new underlying VertexBuffer object is created.
  60751. * 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.
  60752. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60753. *
  60754. * Possible `kind` values :
  60755. * - BABYLON.VertexBuffer.PositionKind
  60756. * - BABYLON.VertexBuffer.UVKind
  60757. * - BABYLON.VertexBuffer.UV2Kind
  60758. * - BABYLON.VertexBuffer.UV3Kind
  60759. * - BABYLON.VertexBuffer.UV4Kind
  60760. * - BABYLON.VertexBuffer.UV5Kind
  60761. * - BABYLON.VertexBuffer.UV6Kind
  60762. * - BABYLON.VertexBuffer.ColorKind
  60763. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60764. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60765. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60766. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60767. *
  60768. * Returns the Mesh.
  60769. */
  60770. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60771. if (this.sourceMesh) {
  60772. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60773. }
  60774. return this.sourceMesh;
  60775. };
  60776. /**
  60777. * Sets the mesh indices.
  60778. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60779. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60780. * This method creates a new index buffer each call.
  60781. * Returns the Mesh.
  60782. */
  60783. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60784. if (totalVertices === void 0) { totalVertices = null; }
  60785. if (this.sourceMesh) {
  60786. this.sourceMesh.setIndices(indices, totalVertices);
  60787. }
  60788. return this.sourceMesh;
  60789. };
  60790. /**
  60791. * Boolean : True if the mesh owns the requested kind of data.
  60792. */
  60793. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60794. return this._sourceMesh.isVerticesDataPresent(kind);
  60795. };
  60796. /**
  60797. * Returns an array of indices (IndicesArray).
  60798. */
  60799. InstancedMesh.prototype.getIndices = function () {
  60800. return this._sourceMesh.getIndices();
  60801. };
  60802. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60803. get: function () {
  60804. return this._sourceMesh._positions;
  60805. },
  60806. enumerable: true,
  60807. configurable: true
  60808. });
  60809. /**
  60810. * Sets a new updated BoundingInfo to the mesh.
  60811. * Returns the mesh.
  60812. */
  60813. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60814. var meshBB = this._sourceMesh.getBoundingInfo();
  60815. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60816. this._updateBoundingInfo();
  60817. return this;
  60818. };
  60819. InstancedMesh.prototype._preActivate = function () {
  60820. if (this._currentLOD) {
  60821. this._currentLOD._preActivate();
  60822. }
  60823. return this;
  60824. };
  60825. InstancedMesh.prototype._activate = function (renderId) {
  60826. if (this._currentLOD) {
  60827. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60828. }
  60829. return this;
  60830. };
  60831. /**
  60832. * Returns the current associated LOD AbstractMesh.
  60833. */
  60834. InstancedMesh.prototype.getLOD = function (camera) {
  60835. if (!camera) {
  60836. return this;
  60837. }
  60838. var boundingInfo = this.getBoundingInfo();
  60839. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60840. if (this._currentLOD === this.sourceMesh) {
  60841. return this;
  60842. }
  60843. return this._currentLOD;
  60844. };
  60845. InstancedMesh.prototype._syncSubMeshes = function () {
  60846. this.releaseSubMeshes();
  60847. if (this._sourceMesh.subMeshes) {
  60848. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60849. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60850. }
  60851. }
  60852. return this;
  60853. };
  60854. InstancedMesh.prototype._generatePointsArray = function () {
  60855. return this._sourceMesh._generatePointsArray();
  60856. };
  60857. /**
  60858. * Creates a new InstancedMesh from the current mesh.
  60859. * - name (string) : the cloned mesh name
  60860. * - newParent (optional Node) : the optional Node to parent the clone to.
  60861. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60862. *
  60863. * Returns the clone.
  60864. */
  60865. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60866. var result = this._sourceMesh.createInstance(name);
  60867. // Deep copy
  60868. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60869. // Bounding info
  60870. this.refreshBoundingInfo();
  60871. // Parent
  60872. if (newParent) {
  60873. result.parent = newParent;
  60874. }
  60875. if (!doNotCloneChildren) {
  60876. // Children
  60877. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60878. var mesh = this.getScene().meshes[index];
  60879. if (mesh.parent === this) {
  60880. mesh.clone(mesh.name, result);
  60881. }
  60882. }
  60883. }
  60884. result.computeWorldMatrix(true);
  60885. return result;
  60886. };
  60887. /**
  60888. * Disposes the InstancedMesh.
  60889. * Returns nothing.
  60890. */
  60891. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60892. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60893. // Remove from mesh
  60894. var index = this._sourceMesh.instances.indexOf(this);
  60895. this._sourceMesh.instances.splice(index, 1);
  60896. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60897. };
  60898. return InstancedMesh;
  60899. }(BABYLON.AbstractMesh));
  60900. BABYLON.InstancedMesh = InstancedMesh;
  60901. })(BABYLON || (BABYLON = {}));
  60902. //# sourceMappingURL=babylon.instancedMesh.js.map
  60903. var BABYLON;
  60904. (function (BABYLON) {
  60905. var LinesMesh = /** @class */ (function (_super) {
  60906. __extends(LinesMesh, _super);
  60907. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60908. if (scene === void 0) { scene = null; }
  60909. if (parent === void 0) { parent = null; }
  60910. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60911. _this.useVertexColor = useVertexColor;
  60912. _this.useVertexAlpha = useVertexAlpha;
  60913. _this.color = new BABYLON.Color3(1, 1, 1);
  60914. _this.alpha = 1;
  60915. if (source) {
  60916. _this.color = source.color.clone();
  60917. _this.alpha = source.alpha;
  60918. _this.useVertexColor = source.useVertexColor;
  60919. _this.useVertexAlpha = source.useVertexAlpha;
  60920. }
  60921. _this._intersectionThreshold = 0.1;
  60922. var defines = [];
  60923. var options = {
  60924. attributes: [BABYLON.VertexBuffer.PositionKind],
  60925. uniforms: ["world", "viewProjection"],
  60926. needAlphaBlending: true,
  60927. defines: defines
  60928. };
  60929. if (useVertexAlpha === false) {
  60930. options.needAlphaBlending = false;
  60931. }
  60932. if (!useVertexColor) {
  60933. options.uniforms.push("color");
  60934. }
  60935. else {
  60936. options.defines.push("#define VERTEXCOLOR");
  60937. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60938. }
  60939. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60940. return _this;
  60941. }
  60942. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60943. /**
  60944. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60945. * This margin is expressed in world space coordinates, so its value may vary.
  60946. * Default value is 0.1
  60947. * @returns the intersection Threshold value.
  60948. */
  60949. get: function () {
  60950. return this._intersectionThreshold;
  60951. },
  60952. /**
  60953. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60954. * This margin is expressed in world space coordinates, so its value may vary.
  60955. * @param value the new threshold to apply
  60956. */
  60957. set: function (value) {
  60958. if (this._intersectionThreshold === value) {
  60959. return;
  60960. }
  60961. this._intersectionThreshold = value;
  60962. if (this.geometry) {
  60963. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60964. }
  60965. },
  60966. enumerable: true,
  60967. configurable: true
  60968. });
  60969. /**
  60970. * Returns the string "LineMesh"
  60971. */
  60972. LinesMesh.prototype.getClassName = function () {
  60973. return "LinesMesh";
  60974. };
  60975. Object.defineProperty(LinesMesh.prototype, "material", {
  60976. get: function () {
  60977. return this._colorShader;
  60978. },
  60979. set: function (value) {
  60980. // Do nothing
  60981. },
  60982. enumerable: true,
  60983. configurable: true
  60984. });
  60985. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60986. get: function () {
  60987. return false;
  60988. },
  60989. enumerable: true,
  60990. configurable: true
  60991. });
  60992. LinesMesh.prototype.createInstance = function (name) {
  60993. throw new Error("LinesMeshes do not support createInstance.");
  60994. };
  60995. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60996. if (!this._geometry) {
  60997. return this;
  60998. }
  60999. // VBOs
  61000. this._geometry._bind(this._colorShader.getEffect());
  61001. // Color
  61002. if (!this.useVertexColor) {
  61003. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61004. }
  61005. return this;
  61006. };
  61007. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61008. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61009. return this;
  61010. }
  61011. var engine = this.getScene().getEngine();
  61012. // Draw order
  61013. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61014. return this;
  61015. };
  61016. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61017. this._colorShader.dispose();
  61018. _super.prototype.dispose.call(this, doNotRecurse);
  61019. };
  61020. /**
  61021. * Returns a new LineMesh object cloned from the current one.
  61022. */
  61023. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61024. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61025. };
  61026. return LinesMesh;
  61027. }(BABYLON.Mesh));
  61028. BABYLON.LinesMesh = LinesMesh;
  61029. })(BABYLON || (BABYLON = {}));
  61030. //# sourceMappingURL=babylon.linesMesh.js.map
  61031. var BABYLON;
  61032. (function (BABYLON) {
  61033. /**
  61034. * Class containing static functions to help procedurally build meshes
  61035. */
  61036. var MeshBuilder = /** @class */ (function () {
  61037. function MeshBuilder() {
  61038. }
  61039. MeshBuilder.updateSideOrientation = function (orientation) {
  61040. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  61041. return BABYLON.Mesh.DOUBLESIDE;
  61042. }
  61043. if (orientation === undefined || orientation === null) {
  61044. return BABYLON.Mesh.FRONTSIDE;
  61045. }
  61046. return orientation;
  61047. };
  61048. /**
  61049. * Creates a box mesh
  61050. * * The parameter `size` sets the size (float) of each box side (default 1)
  61051. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  61052. * * 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)
  61053. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61054. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61055. * * 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
  61056. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61057. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  61058. * @param name defines the name of the mesh
  61059. * @param options defines the options used to create the mesh
  61060. * @param scene defines the hosting scene
  61061. * @returns the box mesh
  61062. */
  61063. MeshBuilder.CreateBox = function (name, options, scene) {
  61064. if (scene === void 0) { scene = null; }
  61065. var box = new BABYLON.Mesh(name, scene);
  61066. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61067. box._originalBuilderSideOrientation = options.sideOrientation;
  61068. var vertexData = BABYLON.VertexData.CreateBox(options);
  61069. vertexData.applyToMesh(box, options.updatable);
  61070. return box;
  61071. };
  61072. /**
  61073. * Creates a sphere mesh
  61074. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61075. * * 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`)
  61076. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61077. * * 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
  61078. * * 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)
  61079. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61080. * * 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
  61081. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61082. * @param name defines the name of the mesh
  61083. * @param options defines the options used to create the mesh
  61084. * @param scene defines the hosting scene
  61085. * @returns the sphere mesh
  61086. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61087. */
  61088. MeshBuilder.CreateSphere = function (name, options, scene) {
  61089. var sphere = new BABYLON.Mesh(name, scene);
  61090. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61091. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61092. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61093. vertexData.applyToMesh(sphere, options.updatable);
  61094. return sphere;
  61095. };
  61096. /**
  61097. * Creates a plane polygonal mesh. By default, this is a disc
  61098. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61099. * * 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
  61100. * * 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
  61101. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61102. * * 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
  61103. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61104. * @param name defines the name of the mesh
  61105. * @param options defines the options used to create the mesh
  61106. * @param scene defines the hosting scene
  61107. * @returns the plane polygonal mesh
  61108. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61109. */
  61110. MeshBuilder.CreateDisc = function (name, options, scene) {
  61111. if (scene === void 0) { scene = null; }
  61112. var disc = new BABYLON.Mesh(name, scene);
  61113. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61114. disc._originalBuilderSideOrientation = options.sideOrientation;
  61115. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61116. vertexData.applyToMesh(disc, options.updatable);
  61117. return disc;
  61118. };
  61119. /**
  61120. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61121. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61122. * * 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`)
  61123. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61124. * * 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
  61125. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61126. * * 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
  61127. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61128. * @param name defines the name of the mesh
  61129. * @param options defines the options used to create the mesh
  61130. * @param scene defines the hosting scene
  61131. * @returns the icosahedron mesh
  61132. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61133. */
  61134. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61135. var sphere = new BABYLON.Mesh(name, scene);
  61136. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61137. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61138. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61139. vertexData.applyToMesh(sphere, options.updatable);
  61140. return sphere;
  61141. };
  61142. ;
  61143. /**
  61144. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61145. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61146. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61147. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61148. * * 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
  61149. * * 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
  61150. * * 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
  61151. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61152. * * 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
  61153. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61154. * * 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
  61155. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61156. * * 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
  61157. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61158. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61159. * @param name defines the name of the mesh
  61160. * @param options defines the options used to create the mesh
  61161. * @param scene defines the hosting scene
  61162. * @returns the ribbon mesh
  61163. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61164. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61165. */
  61166. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61167. if (scene === void 0) { scene = null; }
  61168. var pathArray = options.pathArray;
  61169. var closeArray = options.closeArray;
  61170. var closePath = options.closePath;
  61171. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61172. var instance = options.instance;
  61173. var updatable = options.updatable;
  61174. if (instance) { // existing ribbon instance update
  61175. // positionFunction : ribbon case
  61176. // only pathArray and sideOrientation parameters are taken into account for positions update
  61177. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61178. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61179. var positionFunction = function (positions) {
  61180. var minlg = pathArray[0].length;
  61181. var i = 0;
  61182. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61183. for (var si = 1; si <= ns; si++) {
  61184. for (var p = 0; p < pathArray.length; p++) {
  61185. var path = pathArray[p];
  61186. var l = path.length;
  61187. minlg = (minlg < l) ? minlg : l;
  61188. var j = 0;
  61189. while (j < minlg) {
  61190. positions[i] = path[j].x;
  61191. positions[i + 1] = path[j].y;
  61192. positions[i + 2] = path[j].z;
  61193. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61194. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61195. }
  61196. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61197. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61198. }
  61199. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61200. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61201. }
  61202. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61203. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61204. }
  61205. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61206. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61207. }
  61208. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61209. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61210. }
  61211. j++;
  61212. i += 3;
  61213. }
  61214. if (instance._closePath) {
  61215. positions[i] = path[0].x;
  61216. positions[i + 1] = path[0].y;
  61217. positions[i + 2] = path[0].z;
  61218. i += 3;
  61219. }
  61220. }
  61221. }
  61222. };
  61223. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61224. positionFunction(positions);
  61225. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61226. instance._boundingInfo.update(instance._worldMatrix);
  61227. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61228. if (options.colors) {
  61229. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61230. for (var c = 0; c < options.colors.length; c++) {
  61231. colors[c * 4] = options.colors[c].r;
  61232. colors[c * 4 + 1] = options.colors[c].g;
  61233. colors[c * 4 + 2] = options.colors[c].b;
  61234. colors[c * 4 + 3] = options.colors[c].a;
  61235. }
  61236. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61237. }
  61238. if (options.uvs) {
  61239. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61240. for (var i = 0; i < options.uvs.length; i++) {
  61241. uvs[i * 2] = options.uvs[i].x;
  61242. uvs[i * 2 + 1] = options.uvs[i].y;
  61243. }
  61244. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61245. }
  61246. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61247. var indices = instance.getIndices();
  61248. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61249. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61250. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61251. if (instance._closePath) {
  61252. var indexFirst = 0;
  61253. var indexLast = 0;
  61254. for (var p = 0; p < pathArray.length; p++) {
  61255. indexFirst = instance._idx[p] * 3;
  61256. if (p + 1 < pathArray.length) {
  61257. indexLast = (instance._idx[p + 1] - 1) * 3;
  61258. }
  61259. else {
  61260. indexLast = normals.length - 3;
  61261. }
  61262. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61263. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61264. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61265. normals[indexLast] = normals[indexFirst];
  61266. normals[indexLast + 1] = normals[indexFirst + 1];
  61267. normals[indexLast + 2] = normals[indexFirst + 2];
  61268. }
  61269. }
  61270. if (!(instance.areNormalsFrozen)) {
  61271. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61272. }
  61273. }
  61274. return instance;
  61275. }
  61276. else { // new ribbon creation
  61277. var ribbon = new BABYLON.Mesh(name, scene);
  61278. ribbon._originalBuilderSideOrientation = sideOrientation;
  61279. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61280. if (closePath) {
  61281. ribbon._idx = vertexData._idx;
  61282. }
  61283. ribbon._closePath = closePath;
  61284. ribbon._closeArray = closeArray;
  61285. vertexData.applyToMesh(ribbon, updatable);
  61286. return ribbon;
  61287. }
  61288. };
  61289. /**
  61290. * Creates a cylinder or a cone mesh
  61291. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61292. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61293. * * 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.
  61294. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61295. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61296. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61297. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61298. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61299. * * 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).
  61300. * * 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
  61301. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61302. * * 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
  61303. * * 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.
  61304. * * If `enclose` is false, a ring surface is one element.
  61305. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61306. * * 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
  61307. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61308. * * 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
  61309. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61310. * @param name defines the name of the mesh
  61311. * @param options defines the options used to create the mesh
  61312. * @param scene defines the hosting scene
  61313. * @returns the cylinder mesh
  61314. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61315. */
  61316. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61317. var cylinder = new BABYLON.Mesh(name, scene);
  61318. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61319. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61320. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61321. vertexData.applyToMesh(cylinder, options.updatable);
  61322. return cylinder;
  61323. };
  61324. /**
  61325. * Creates a torus mesh
  61326. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61327. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61328. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61329. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61330. * * 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
  61331. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61332. * @param name defines the name of the mesh
  61333. * @param options defines the options used to create the mesh
  61334. * @param scene defines the hosting scene
  61335. * @returns the torus mesh
  61336. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61337. */
  61338. MeshBuilder.CreateTorus = function (name, options, scene) {
  61339. var torus = new BABYLON.Mesh(name, scene);
  61340. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61341. torus._originalBuilderSideOrientation = options.sideOrientation;
  61342. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61343. vertexData.applyToMesh(torus, options.updatable);
  61344. return torus;
  61345. };
  61346. /**
  61347. * Creates a torus knot mesh
  61348. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61349. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61350. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61351. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61352. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61353. * * 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
  61354. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61355. * @param name defines the name of the mesh
  61356. * @param options defines the options used to create the mesh
  61357. * @param scene defines the hosting scene
  61358. * @returns the torus knot mesh
  61359. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61360. */
  61361. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61362. var torusKnot = new BABYLON.Mesh(name, scene);
  61363. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61364. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61365. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61366. vertexData.applyToMesh(torusKnot, options.updatable);
  61367. return torusKnot;
  61368. };
  61369. /**
  61370. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61371. * * 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
  61372. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61373. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61374. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61375. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61376. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61377. * * 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
  61378. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61379. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61380. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61381. * @param name defines the name of the new line system
  61382. * @param options defines the options used to create the line system
  61383. * @param scene defines the hosting scene
  61384. * @returns a new line system mesh
  61385. */
  61386. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61387. var instance = options.instance;
  61388. var lines = options.lines;
  61389. var colors = options.colors;
  61390. if (instance) { // lines update
  61391. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61392. var vertexColor;
  61393. var lineColors;
  61394. if (colors) {
  61395. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61396. }
  61397. var i = 0;
  61398. var c = 0;
  61399. for (var l = 0; l < lines.length; l++) {
  61400. var points = lines[l];
  61401. for (var p = 0; p < points.length; p++) {
  61402. positions[i] = points[p].x;
  61403. positions[i + 1] = points[p].y;
  61404. positions[i + 2] = points[p].z;
  61405. if (colors && vertexColor) {
  61406. lineColors = colors[l];
  61407. vertexColor[c] = lineColors[p].r;
  61408. vertexColor[c + 1] = lineColors[p].g;
  61409. vertexColor[c + 2] = lineColors[p].b;
  61410. vertexColor[c + 3] = lineColors[p].a;
  61411. c += 4;
  61412. }
  61413. i += 3;
  61414. }
  61415. }
  61416. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61417. if (colors && vertexColor) {
  61418. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61419. }
  61420. return instance;
  61421. }
  61422. // line system creation
  61423. var useVertexColor = (colors) ? true : false;
  61424. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61425. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61426. vertexData.applyToMesh(lineSystem, options.updatable);
  61427. return lineSystem;
  61428. };
  61429. /**
  61430. * Creates a line mesh
  61431. * 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
  61432. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61433. * * The parameter `points` is an array successive Vector3
  61434. * * 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
  61435. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61436. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61437. * * When updating an instance, remember that only point positions can change, not the number of points
  61438. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61439. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61440. * @param name defines the name of the new line system
  61441. * @param options defines the options used to create the line system
  61442. * @param scene defines the hosting scene
  61443. * @returns a new line mesh
  61444. */
  61445. MeshBuilder.CreateLines = function (name, options, scene) {
  61446. if (scene === void 0) { scene = null; }
  61447. var colors = (options.colors) ? [options.colors] : null;
  61448. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61449. return lines;
  61450. };
  61451. /**
  61452. * Creates a dashed line mesh
  61453. * * 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
  61454. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61455. * * The parameter `points` is an array successive Vector3
  61456. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61457. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61458. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61459. * * 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
  61460. * * When updating an instance, remember that only point positions can change, not the number of points
  61461. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61462. * @param name defines the name of the mesh
  61463. * @param options defines the options used to create the mesh
  61464. * @param scene defines the hosting scene
  61465. * @returns the dashed line mesh
  61466. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61467. */
  61468. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61469. if (scene === void 0) { scene = null; }
  61470. var points = options.points;
  61471. var instance = options.instance;
  61472. var gapSize = options.gapSize || 1;
  61473. var dashSize = options.dashSize || 3;
  61474. if (instance) { // dashed lines update
  61475. var positionFunction = function (positions) {
  61476. var curvect = BABYLON.Vector3.Zero();
  61477. var nbSeg = positions.length / 6;
  61478. var lg = 0;
  61479. var nb = 0;
  61480. var shft = 0;
  61481. var dashshft = 0;
  61482. var curshft = 0;
  61483. var p = 0;
  61484. var i = 0;
  61485. var j = 0;
  61486. for (i = 0; i < points.length - 1; i++) {
  61487. points[i + 1].subtractToRef(points[i], curvect);
  61488. lg += curvect.length();
  61489. }
  61490. shft = lg / nbSeg;
  61491. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61492. for (i = 0; i < points.length - 1; i++) {
  61493. points[i + 1].subtractToRef(points[i], curvect);
  61494. nb = Math.floor(curvect.length() / shft);
  61495. curvect.normalize();
  61496. j = 0;
  61497. while (j < nb && p < positions.length) {
  61498. curshft = shft * j;
  61499. positions[p] = points[i].x + curshft * curvect.x;
  61500. positions[p + 1] = points[i].y + curshft * curvect.y;
  61501. positions[p + 2] = points[i].z + curshft * curvect.z;
  61502. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61503. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61504. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61505. p += 6;
  61506. j++;
  61507. }
  61508. }
  61509. while (p < positions.length) {
  61510. positions[p] = points[i].x;
  61511. positions[p + 1] = points[i].y;
  61512. positions[p + 2] = points[i].z;
  61513. p += 3;
  61514. }
  61515. };
  61516. instance.updateMeshPositions(positionFunction, false);
  61517. return instance;
  61518. }
  61519. // dashed lines creation
  61520. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61521. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61522. vertexData.applyToMesh(dashedLines, options.updatable);
  61523. dashedLines.dashSize = dashSize;
  61524. dashedLines.gapSize = gapSize;
  61525. return dashedLines;
  61526. };
  61527. /**
  61528. * 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.
  61529. * * 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.
  61530. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61531. * * 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.
  61532. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61533. * * 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
  61534. * * 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
  61535. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61536. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61537. * * 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
  61538. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61539. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61540. * @param name defines the name of the mesh
  61541. * @param options defines the options used to create the mesh
  61542. * @param scene defines the hosting scene
  61543. * @returns the extruded shape mesh
  61544. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61545. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61546. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61547. */
  61548. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61549. if (scene === void 0) { scene = null; }
  61550. var path = options.path;
  61551. var shape = options.shape;
  61552. var scale = options.scale || 1;
  61553. var rotation = options.rotation || 0;
  61554. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61555. var updatable = options.updatable;
  61556. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61557. var instance = options.instance || null;
  61558. var invertUV = options.invertUV || false;
  61559. 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);
  61560. };
  61561. /**
  61562. * Creates an custom extruded shape mesh.
  61563. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61564. * * 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.
  61565. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61566. * * 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
  61567. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61568. * * 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
  61569. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61570. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61571. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61572. * * 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
  61573. * * 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
  61574. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61575. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61576. * * 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
  61577. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61578. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61579. * @param name defines the name of the mesh
  61580. * @param options defines the options used to create the mesh
  61581. * @param scene defines the hosting scene
  61582. * @returns the custom extruded shape mesh
  61583. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61584. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61585. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61586. */
  61587. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61588. var path = options.path;
  61589. var shape = options.shape;
  61590. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61591. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61592. var ribbonCloseArray = options.ribbonCloseArray || false;
  61593. var ribbonClosePath = options.ribbonClosePath || false;
  61594. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61595. var updatable = options.updatable;
  61596. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61597. var instance = options.instance;
  61598. var invertUV = options.invertUV || false;
  61599. 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);
  61600. };
  61601. /**
  61602. * Creates lathe mesh.
  61603. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61604. * * 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
  61605. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61606. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61607. * * 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
  61608. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61609. * * 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
  61610. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61611. * * 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
  61612. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61613. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61614. * @param name defines the name of the mesh
  61615. * @param options defines the options used to create the mesh
  61616. * @param scene defines the hosting scene
  61617. * @returns the lathe mesh
  61618. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61619. */
  61620. MeshBuilder.CreateLathe = function (name, options, scene) {
  61621. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61622. var closed = (options.closed === undefined) ? true : options.closed;
  61623. var shape = options.shape;
  61624. var radius = options.radius || 1;
  61625. var tessellation = options.tessellation || 64;
  61626. var updatable = options.updatable;
  61627. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61628. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61629. var pi2 = Math.PI * 2;
  61630. var paths = new Array();
  61631. var invertUV = options.invertUV || false;
  61632. var i = 0;
  61633. var p = 0;
  61634. var step = pi2 / tessellation * arc;
  61635. var rotated;
  61636. var path = new Array();
  61637. for (i = 0; i <= tessellation; i++) {
  61638. var path = [];
  61639. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61640. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61641. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61642. }
  61643. for (p = 0; p < shape.length; p++) {
  61644. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61645. path.push(rotated);
  61646. }
  61647. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61648. 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));
  61649. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61650. }
  61651. paths.push(path);
  61652. }
  61653. // lathe ribbon
  61654. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61655. return lathe;
  61656. };
  61657. /**
  61658. * Creates a plane mesh
  61659. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61660. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61661. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61662. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61663. * * 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
  61664. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61665. * @param name defines the name of the mesh
  61666. * @param options defines the options used to create the mesh
  61667. * @param scene defines the hosting scene
  61668. * @returns the plane mesh
  61669. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61670. */
  61671. MeshBuilder.CreatePlane = function (name, options, scene) {
  61672. var plane = new BABYLON.Mesh(name, scene);
  61673. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61674. plane._originalBuilderSideOrientation = options.sideOrientation;
  61675. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61676. vertexData.applyToMesh(plane, options.updatable);
  61677. if (options.sourcePlane) {
  61678. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61679. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61680. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61681. plane.rotate(vectorProduct, product);
  61682. }
  61683. return plane;
  61684. };
  61685. /**
  61686. * Creates a ground mesh
  61687. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61688. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61689. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61690. * @param name defines the name of the mesh
  61691. * @param options defines the options used to create the mesh
  61692. * @param scene defines the hosting scene
  61693. * @returns the ground mesh
  61694. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61695. */
  61696. MeshBuilder.CreateGround = function (name, options, scene) {
  61697. var ground = new BABYLON.GroundMesh(name, scene);
  61698. ground._setReady(false);
  61699. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61700. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61701. ground._width = options.width || 1;
  61702. ground._height = options.height || 1;
  61703. ground._maxX = ground._width / 2;
  61704. ground._maxZ = ground._height / 2;
  61705. ground._minX = -ground._maxX;
  61706. ground._minZ = -ground._maxZ;
  61707. var vertexData = BABYLON.VertexData.CreateGround(options);
  61708. vertexData.applyToMesh(ground, options.updatable);
  61709. ground._setReady(true);
  61710. return ground;
  61711. };
  61712. /**
  61713. * Creates a tiled ground mesh
  61714. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61715. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61716. * * 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
  61717. * * 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
  61718. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61719. * @param name defines the name of the mesh
  61720. * @param options defines the options used to create the mesh
  61721. * @param scene defines the hosting scene
  61722. * @returns the tiled ground mesh
  61723. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61724. */
  61725. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61726. var tiledGround = new BABYLON.Mesh(name, scene);
  61727. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61728. vertexData.applyToMesh(tiledGround, options.updatable);
  61729. return tiledGround;
  61730. };
  61731. /**
  61732. * Creates a ground mesh from a height map
  61733. * * The parameter `url` sets the URL of the height map image resource.
  61734. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61735. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61736. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61737. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61738. * * 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.
  61739. * * 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).
  61740. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61741. * @param name defines the name of the mesh
  61742. * @param url defines the url to the height map
  61743. * @param options defines the options used to create the mesh
  61744. * @param scene defines the hosting scene
  61745. * @returns the ground mesh
  61746. * @see http://doc.babylonjs.com/babylon101/height_map
  61747. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61748. */
  61749. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61750. var width = options.width || 10.0;
  61751. var height = options.height || 10.0;
  61752. var subdivisions = options.subdivisions || 1 | 0;
  61753. var minHeight = options.minHeight || 0.0;
  61754. var maxHeight = options.maxHeight || 1.0;
  61755. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61756. var updatable = options.updatable;
  61757. var onReady = options.onReady;
  61758. var ground = new BABYLON.GroundMesh(name, scene);
  61759. ground._subdivisionsX = subdivisions;
  61760. ground._subdivisionsY = subdivisions;
  61761. ground._width = width;
  61762. ground._height = height;
  61763. ground._maxX = ground._width / 2.0;
  61764. ground._maxZ = ground._height / 2.0;
  61765. ground._minX = -ground._maxX;
  61766. ground._minZ = -ground._maxZ;
  61767. ground._setReady(false);
  61768. var onload = function (img) {
  61769. // Getting height map data
  61770. var canvas = document.createElement("canvas");
  61771. var context = canvas.getContext("2d");
  61772. if (!context) {
  61773. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61774. }
  61775. if (scene.isDisposed) {
  61776. return;
  61777. }
  61778. var bufferWidth = img.width;
  61779. var bufferHeight = img.height;
  61780. canvas.width = bufferWidth;
  61781. canvas.height = bufferHeight;
  61782. context.drawImage(img, 0, 0);
  61783. // Create VertexData from map data
  61784. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61785. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61786. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61787. width: width, height: height,
  61788. subdivisions: subdivisions,
  61789. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61790. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61791. });
  61792. vertexData.applyToMesh(ground, updatable);
  61793. //execute ready callback, if set
  61794. if (onReady) {
  61795. onReady(ground);
  61796. }
  61797. ground._setReady(true);
  61798. };
  61799. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61800. return ground;
  61801. };
  61802. /**
  61803. * Creates a polygon mesh
  61804. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61805. * * 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
  61806. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61807. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61808. * * 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)
  61809. * * Remember you can only change the shape positions, not their number when updating a polygon
  61810. * @param name defines the name of the mesh
  61811. * @param options defines the options used to create the mesh
  61812. * @param scene defines the hosting scene
  61813. * @returns the polygon mesh
  61814. */
  61815. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61816. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61817. var shape = options.shape;
  61818. var holes = options.holes || [];
  61819. var depth = options.depth || 0;
  61820. var contours = [];
  61821. var hole = [];
  61822. for (var i = 0; i < shape.length; i++) {
  61823. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61824. }
  61825. var epsilon = 0.00000001;
  61826. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61827. contours.pop();
  61828. }
  61829. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61830. for (var hNb = 0; hNb < holes.length; hNb++) {
  61831. hole = [];
  61832. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61833. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61834. }
  61835. polygonTriangulation.addHole(hole);
  61836. }
  61837. var polygon = polygonTriangulation.build(options.updatable, depth);
  61838. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61839. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61840. vertexData.applyToMesh(polygon, options.updatable);
  61841. return polygon;
  61842. };
  61843. ;
  61844. /**
  61845. * Creates an extruded polygon mesh, with depth in the Y direction.
  61846. * * 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)
  61847. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61848. * @param name defines the name of the mesh
  61849. * @param options defines the options used to create the mesh
  61850. * @param scene defines the hosting scene
  61851. * @returns the polygon mesh
  61852. */
  61853. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61854. return MeshBuilder.CreatePolygon(name, options, scene);
  61855. };
  61856. ;
  61857. /**
  61858. * Creates a tube mesh.
  61859. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61860. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61861. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61862. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61863. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61864. * * 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)
  61865. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61866. * * 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
  61867. * * 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
  61868. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61869. * * 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
  61870. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61871. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61872. * @param name defines the name of the mesh
  61873. * @param options defines the options used to create the mesh
  61874. * @param scene defines the hosting scene
  61875. * @returns the tube mesh
  61876. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61877. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61878. */
  61879. MeshBuilder.CreateTube = function (name, options, scene) {
  61880. var path = options.path;
  61881. var instance = options.instance;
  61882. var radius = 1.0;
  61883. if (instance) {
  61884. radius = instance.radius;
  61885. }
  61886. if (options.radius !== undefined) {
  61887. radius = options.radius;
  61888. }
  61889. ;
  61890. var tessellation = options.tessellation || 64 | 0;
  61891. var radiusFunction = options.radiusFunction || null;
  61892. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61893. var invertUV = options.invertUV || false;
  61894. var updatable = options.updatable;
  61895. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61896. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61897. // tube geometry
  61898. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61899. var tangents = path3D.getTangents();
  61900. var normals = path3D.getNormals();
  61901. var distances = path3D.getDistances();
  61902. var pi2 = Math.PI * 2;
  61903. var step = pi2 / tessellation * arc;
  61904. var returnRadius = function () { return radius; };
  61905. var radiusFunctionFinal = radiusFunction || returnRadius;
  61906. var circlePath;
  61907. var rad;
  61908. var normal;
  61909. var rotated;
  61910. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61911. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61912. for (var i = 0; i < path.length; i++) {
  61913. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61914. circlePath = Array(); // current circle array
  61915. normal = normals[i]; // current normal
  61916. for (var t = 0; t < tessellation; t++) {
  61917. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61918. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61919. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61920. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61921. circlePath[t] = rotated;
  61922. }
  61923. circlePaths[index] = circlePath;
  61924. index++;
  61925. }
  61926. // cap
  61927. var capPath = function (nbPoints, pathIndex) {
  61928. var pointCap = Array();
  61929. for (var i = 0; i < nbPoints; i++) {
  61930. pointCap.push(path[pathIndex]);
  61931. }
  61932. return pointCap;
  61933. };
  61934. switch (cap) {
  61935. case BABYLON.Mesh.NO_CAP:
  61936. break;
  61937. case BABYLON.Mesh.CAP_START:
  61938. circlePaths[0] = capPath(tessellation, 0);
  61939. circlePaths[1] = circlePaths[2].slice(0);
  61940. break;
  61941. case BABYLON.Mesh.CAP_END:
  61942. circlePaths[index] = circlePaths[index - 1].slice(0);
  61943. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61944. break;
  61945. case BABYLON.Mesh.CAP_ALL:
  61946. circlePaths[0] = capPath(tessellation, 0);
  61947. circlePaths[1] = circlePaths[2].slice(0);
  61948. circlePaths[index] = circlePaths[index - 1].slice(0);
  61949. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61950. break;
  61951. default:
  61952. break;
  61953. }
  61954. return circlePaths;
  61955. };
  61956. var path3D;
  61957. var pathArray;
  61958. if (instance) { // tube update
  61959. var arc = options.arc || instance.arc;
  61960. path3D = (instance.path3D).update(path);
  61961. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61962. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61963. instance.path3D = path3D;
  61964. instance.pathArray = pathArray;
  61965. instance.arc = arc;
  61966. instance.radius = radius;
  61967. return instance;
  61968. }
  61969. // tube creation
  61970. path3D = new BABYLON.Path3D(path);
  61971. var newPathArray = new Array();
  61972. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61973. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61974. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61975. tube.pathArray = pathArray;
  61976. tube.path3D = path3D;
  61977. tube.tessellation = tessellation;
  61978. tube.cap = cap;
  61979. tube.arc = options.arc;
  61980. tube.radius = radius;
  61981. return tube;
  61982. };
  61983. /**
  61984. * Creates a polyhedron mesh
  61985. * * 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
  61986. * * The parameter `size` (positive float, default 1) sets the polygon size
  61987. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61988. * * 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`
  61989. * * 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
  61990. * * 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)`)
  61991. * * 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
  61992. * * 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
  61993. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61994. * * 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
  61995. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61996. * @param name defines the name of the mesh
  61997. * @param options defines the options used to create the mesh
  61998. * @param scene defines the hosting scene
  61999. * @returns the polyhedron mesh
  62000. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62001. */
  62002. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62003. var polyhedron = new BABYLON.Mesh(name, scene);
  62004. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62005. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62006. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62007. vertexData.applyToMesh(polyhedron, options.updatable);
  62008. return polyhedron;
  62009. };
  62010. /**
  62011. * Creates a decal mesh.
  62012. * 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
  62013. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62014. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62015. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62016. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62017. * @param name defines the name of the mesh
  62018. * @param sourceMesh defines the mesh where the decal must be applied
  62019. * @param options defines the options used to create the mesh
  62020. * @param scene defines the hosting scene
  62021. * @returns the decal mesh
  62022. * @see http://doc.babylonjs.com/how_to/decals
  62023. */
  62024. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  62025. var indices = sourceMesh.getIndices();
  62026. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62027. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62028. var position = options.position || BABYLON.Vector3.Zero();
  62029. var normal = options.normal || BABYLON.Vector3.Up();
  62030. var size = options.size || BABYLON.Vector3.One();
  62031. var angle = options.angle || 0;
  62032. // Getting correct rotation
  62033. if (!normal) {
  62034. var target = new BABYLON.Vector3(0, 0, 1);
  62035. var camera = sourceMesh.getScene().activeCamera;
  62036. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62037. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62038. }
  62039. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  62040. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  62041. var pitch = Math.atan2(normal.y, len);
  62042. // Matrix
  62043. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  62044. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  62045. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  62046. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  62047. var vertexData = new BABYLON.VertexData();
  62048. vertexData.indices = [];
  62049. vertexData.positions = [];
  62050. vertexData.normals = [];
  62051. vertexData.uvs = [];
  62052. var currentVertexDataIndex = 0;
  62053. var extractDecalVector3 = function (indexId) {
  62054. var result = new BABYLON.PositionNormalVertex();
  62055. if (!indices || !positions || !normals) {
  62056. return result;
  62057. }
  62058. var vertexId = indices[indexId];
  62059. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  62060. // Send vector to decal local world
  62061. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  62062. // Get normal
  62063. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62064. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62065. return result;
  62066. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62067. var clip = function (vertices, axis) {
  62068. if (vertices.length === 0) {
  62069. return vertices;
  62070. }
  62071. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62072. var clipVertices = function (v0, v1) {
  62073. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62074. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62075. };
  62076. var result = new Array();
  62077. for (var index = 0; index < vertices.length; index += 3) {
  62078. var v1Out;
  62079. var v2Out;
  62080. var v3Out;
  62081. var total = 0;
  62082. var nV1 = null;
  62083. var nV2 = null;
  62084. var nV3 = null;
  62085. var nV4 = null;
  62086. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62087. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62088. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62089. v1Out = d1 > 0;
  62090. v2Out = d2 > 0;
  62091. v3Out = d3 > 0;
  62092. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62093. switch (total) {
  62094. case 0:
  62095. result.push(vertices[index]);
  62096. result.push(vertices[index + 1]);
  62097. result.push(vertices[index + 2]);
  62098. break;
  62099. case 1:
  62100. if (v1Out) {
  62101. nV1 = vertices[index + 1];
  62102. nV2 = vertices[index + 2];
  62103. nV3 = clipVertices(vertices[index], nV1);
  62104. nV4 = clipVertices(vertices[index], nV2);
  62105. }
  62106. if (v2Out) {
  62107. nV1 = vertices[index];
  62108. nV2 = vertices[index + 2];
  62109. nV3 = clipVertices(vertices[index + 1], nV1);
  62110. nV4 = clipVertices(vertices[index + 1], nV2);
  62111. result.push(nV3);
  62112. result.push(nV2.clone());
  62113. result.push(nV1.clone());
  62114. result.push(nV2.clone());
  62115. result.push(nV3.clone());
  62116. result.push(nV4);
  62117. break;
  62118. }
  62119. if (v3Out) {
  62120. nV1 = vertices[index];
  62121. nV2 = vertices[index + 1];
  62122. nV3 = clipVertices(vertices[index + 2], nV1);
  62123. nV4 = clipVertices(vertices[index + 2], nV2);
  62124. }
  62125. if (nV1 && nV2 && nV3 && nV4) {
  62126. result.push(nV1.clone());
  62127. result.push(nV2.clone());
  62128. result.push(nV3);
  62129. result.push(nV4);
  62130. result.push(nV3.clone());
  62131. result.push(nV2.clone());
  62132. }
  62133. break;
  62134. case 2:
  62135. if (!v1Out) {
  62136. nV1 = vertices[index].clone();
  62137. nV2 = clipVertices(nV1, vertices[index + 1]);
  62138. nV3 = clipVertices(nV1, vertices[index + 2]);
  62139. result.push(nV1);
  62140. result.push(nV2);
  62141. result.push(nV3);
  62142. }
  62143. if (!v2Out) {
  62144. nV1 = vertices[index + 1].clone();
  62145. nV2 = clipVertices(nV1, vertices[index + 2]);
  62146. nV3 = clipVertices(nV1, vertices[index]);
  62147. result.push(nV1);
  62148. result.push(nV2);
  62149. result.push(nV3);
  62150. }
  62151. if (!v3Out) {
  62152. nV1 = vertices[index + 2].clone();
  62153. nV2 = clipVertices(nV1, vertices[index]);
  62154. nV3 = clipVertices(nV1, vertices[index + 1]);
  62155. result.push(nV1);
  62156. result.push(nV2);
  62157. result.push(nV3);
  62158. }
  62159. break;
  62160. case 3:
  62161. break;
  62162. }
  62163. }
  62164. return result;
  62165. };
  62166. for (var index = 0; index < indices.length; index += 3) {
  62167. var faceVertices = new Array();
  62168. faceVertices.push(extractDecalVector3(index));
  62169. faceVertices.push(extractDecalVector3(index + 1));
  62170. faceVertices.push(extractDecalVector3(index + 2));
  62171. // Clip
  62172. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62173. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62174. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62175. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62176. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62177. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62178. if (faceVertices.length === 0) {
  62179. continue;
  62180. }
  62181. // Add UVs and get back to world
  62182. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62183. var vertex = faceVertices[vIndex];
  62184. //TODO check for Int32Array | Uint32Array | Uint16Array
  62185. vertexData.indices.push(currentVertexDataIndex);
  62186. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62187. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62188. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62189. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62190. currentVertexDataIndex++;
  62191. }
  62192. }
  62193. // Return mesh
  62194. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62195. vertexData.applyToMesh(decal);
  62196. decal.position = position.clone();
  62197. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62198. return decal;
  62199. };
  62200. // Privates
  62201. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62202. // extrusion geometry
  62203. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62204. var tangents = path3D.getTangents();
  62205. var normals = path3D.getNormals();
  62206. var binormals = path3D.getBinormals();
  62207. var distances = path3D.getDistances();
  62208. var angle = 0;
  62209. var returnScale = function () { return scale !== null ? scale : 1; };
  62210. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62211. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62212. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62213. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62214. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62215. for (var i = 0; i < curve.length; i++) {
  62216. var shapePath = new Array();
  62217. var angleStep = rotate(i, distances[i]);
  62218. var scaleRatio = scl(i, distances[i]);
  62219. for (var p = 0; p < shape.length; p++) {
  62220. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62221. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62222. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62223. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62224. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62225. shapePath[p] = rotated;
  62226. }
  62227. shapePaths[index] = shapePath;
  62228. angle += angleStep;
  62229. index++;
  62230. }
  62231. // cap
  62232. var capPath = function (shapePath) {
  62233. var pointCap = Array();
  62234. var barycenter = BABYLON.Vector3.Zero();
  62235. var i;
  62236. for (i = 0; i < shapePath.length; i++) {
  62237. barycenter.addInPlace(shapePath[i]);
  62238. }
  62239. barycenter.scaleInPlace(1.0 / shapePath.length);
  62240. for (i = 0; i < shapePath.length; i++) {
  62241. pointCap.push(barycenter);
  62242. }
  62243. return pointCap;
  62244. };
  62245. switch (cap) {
  62246. case BABYLON.Mesh.NO_CAP:
  62247. break;
  62248. case BABYLON.Mesh.CAP_START:
  62249. shapePaths[0] = capPath(shapePaths[2]);
  62250. shapePaths[1] = shapePaths[2];
  62251. break;
  62252. case BABYLON.Mesh.CAP_END:
  62253. shapePaths[index] = shapePaths[index - 1];
  62254. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62255. break;
  62256. case BABYLON.Mesh.CAP_ALL:
  62257. shapePaths[0] = capPath(shapePaths[2]);
  62258. shapePaths[1] = shapePaths[2];
  62259. shapePaths[index] = shapePaths[index - 1];
  62260. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62261. break;
  62262. default:
  62263. break;
  62264. }
  62265. return shapePaths;
  62266. };
  62267. var path3D;
  62268. var pathArray;
  62269. if (instance) { // instance update
  62270. path3D = (instance.path3D).update(curve);
  62271. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62272. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62273. return instance;
  62274. }
  62275. // extruded shape creation
  62276. path3D = new BABYLON.Path3D(curve);
  62277. var newShapePaths = new Array();
  62278. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62279. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62280. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62281. extrudedGeneric.pathArray = pathArray;
  62282. extrudedGeneric.path3D = path3D;
  62283. extrudedGeneric.cap = cap;
  62284. return extrudedGeneric;
  62285. };
  62286. return MeshBuilder;
  62287. }());
  62288. BABYLON.MeshBuilder = MeshBuilder;
  62289. })(BABYLON || (BABYLON = {}));
  62290. //# sourceMappingURL=babylon.meshBuilder.js.map
  62291. var BABYLON;
  62292. (function (BABYLON) {
  62293. /**
  62294. * Draco compression (https://google.github.io/draco/)
  62295. *
  62296. * This class wraps the Draco module.
  62297. *
  62298. * **Encoder**
  62299. *
  62300. * The encoder is not currently implemented.
  62301. *
  62302. * **Decoder**
  62303. *
  62304. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62305. *
  62306. * To update the configuration, use the following code:
  62307. * ```javascript
  62308. * BABYLON.DracoCompression.Configuration = {
  62309. * decoder: {
  62310. * wasmUrl: "<url to the WebAssembly library>",
  62311. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62312. * fallbackUrl: "<url to the fallback JavaScript library>",
  62313. * }
  62314. * };
  62315. * ```
  62316. *
  62317. * 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.
  62318. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62319. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62320. *
  62321. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62322. * ```javascript
  62323. * var dracoCompression = new BABYLON.DracoCompression();
  62324. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62325. * [BABYLON.VertexBuffer.PositionKind]: 0
  62326. * });
  62327. * ```
  62328. *
  62329. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62330. */
  62331. var DracoCompression = /** @class */ (function () {
  62332. /**
  62333. * Constructor
  62334. */
  62335. function DracoCompression() {
  62336. }
  62337. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62338. /**
  62339. * Returns true if the decoder is available.
  62340. */
  62341. get: function () {
  62342. if (typeof DracoDecoderModule !== "undefined") {
  62343. return true;
  62344. }
  62345. var decoder = DracoCompression.Configuration.decoder;
  62346. if (decoder) {
  62347. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62348. return true;
  62349. }
  62350. if (decoder.fallbackUrl) {
  62351. return true;
  62352. }
  62353. }
  62354. return false;
  62355. },
  62356. enumerable: true,
  62357. configurable: true
  62358. });
  62359. /**
  62360. * Stop all async operations and release resources.
  62361. */
  62362. DracoCompression.prototype.dispose = function () {
  62363. };
  62364. /**
  62365. * Decode Draco compressed mesh data to vertex data.
  62366. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62367. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62368. * @returns A promise that resolves with the decoded vertex data
  62369. */
  62370. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62371. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62372. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62373. var module = wrappedModule.module;
  62374. var vertexData = new BABYLON.VertexData();
  62375. var buffer = new module.DecoderBuffer();
  62376. buffer.Init(dataView, dataView.byteLength);
  62377. var decoder = new module.Decoder();
  62378. var geometry;
  62379. var status;
  62380. try {
  62381. var type = decoder.GetEncodedGeometryType(buffer);
  62382. switch (type) {
  62383. case module.TRIANGULAR_MESH:
  62384. geometry = new module.Mesh();
  62385. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62386. break;
  62387. case module.POINT_CLOUD:
  62388. geometry = new module.PointCloud();
  62389. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62390. break;
  62391. default:
  62392. throw new Error("Invalid geometry type " + type);
  62393. }
  62394. if (!status.ok() || !geometry.ptr) {
  62395. throw new Error(status.error_msg());
  62396. }
  62397. var numPoints = geometry.num_points();
  62398. if (type === module.TRIANGULAR_MESH) {
  62399. var numFaces = geometry.num_faces();
  62400. var faceIndices = new module.DracoInt32Array();
  62401. try {
  62402. var indices = new Uint32Array(numFaces * 3);
  62403. for (var i = 0; i < numFaces; i++) {
  62404. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62405. var offset = i * 3;
  62406. indices[offset + 0] = faceIndices.GetValue(0);
  62407. indices[offset + 1] = faceIndices.GetValue(1);
  62408. indices[offset + 2] = faceIndices.GetValue(2);
  62409. }
  62410. vertexData.indices = indices;
  62411. }
  62412. finally {
  62413. module.destroy(faceIndices);
  62414. }
  62415. }
  62416. for (var kind in attributes) {
  62417. var uniqueId = attributes[kind];
  62418. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62419. var dracoData = new module.DracoFloat32Array();
  62420. try {
  62421. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62422. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62423. for (var i = 0; i < babylonData.length; i++) {
  62424. babylonData[i] = dracoData.GetValue(i);
  62425. }
  62426. vertexData.set(babylonData, kind);
  62427. }
  62428. finally {
  62429. module.destroy(dracoData);
  62430. }
  62431. }
  62432. }
  62433. finally {
  62434. if (geometry) {
  62435. module.destroy(geometry);
  62436. }
  62437. module.destroy(decoder);
  62438. module.destroy(buffer);
  62439. }
  62440. return vertexData;
  62441. });
  62442. };
  62443. DracoCompression._GetDecoderModule = function () {
  62444. if (!DracoCompression._DecoderModulePromise) {
  62445. var promise = null;
  62446. var config_1 = {};
  62447. if (typeof DracoDecoderModule !== "undefined") {
  62448. promise = Promise.resolve();
  62449. }
  62450. else {
  62451. var decoder = DracoCompression.Configuration.decoder;
  62452. if (decoder) {
  62453. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62454. promise = Promise.all([
  62455. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62456. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62457. config_1.wasmBinary = data;
  62458. })
  62459. ]);
  62460. }
  62461. else if (decoder.fallbackUrl) {
  62462. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62463. }
  62464. }
  62465. }
  62466. if (!promise) {
  62467. throw new Error("Draco decoder module is not available");
  62468. }
  62469. DracoCompression._DecoderModulePromise = promise.then(function () {
  62470. return new Promise(function (resolve) {
  62471. config_1.onModuleLoaded = function (decoderModule) {
  62472. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62473. resolve({ module: decoderModule });
  62474. };
  62475. DracoDecoderModule(config_1);
  62476. });
  62477. });
  62478. }
  62479. return DracoCompression._DecoderModulePromise;
  62480. };
  62481. DracoCompression._LoadScriptAsync = function (url) {
  62482. return new Promise(function (resolve, reject) {
  62483. BABYLON.Tools.LoadScript(url, function () {
  62484. resolve();
  62485. }, function (message) {
  62486. reject(new Error(message));
  62487. });
  62488. });
  62489. };
  62490. DracoCompression._LoadFileAsync = function (url) {
  62491. return new Promise(function (resolve, reject) {
  62492. BABYLON.Tools.LoadFile(url, function (data) {
  62493. resolve(data);
  62494. }, undefined, undefined, true, function (request, exception) {
  62495. reject(exception);
  62496. });
  62497. });
  62498. };
  62499. /**
  62500. * The configuration. Defaults to the following urls:
  62501. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62502. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62503. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62504. */
  62505. DracoCompression.Configuration = {
  62506. decoder: {
  62507. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62508. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62509. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62510. }
  62511. };
  62512. return DracoCompression;
  62513. }());
  62514. BABYLON.DracoCompression = DracoCompression;
  62515. })(BABYLON || (BABYLON = {}));
  62516. //# sourceMappingURL=babylon.dracoCompression.js.map
  62517. var BABYLON;
  62518. (function (BABYLON) {
  62519. var AudioEngine = /** @class */ (function () {
  62520. function AudioEngine() {
  62521. this._audioContext = null;
  62522. this._audioContextInitialized = false;
  62523. this.canUseWebAudio = false;
  62524. this.WarnedWebAudioUnsupported = false;
  62525. this.unlocked = false;
  62526. this.isMP3supported = false;
  62527. this.isOGGsupported = false;
  62528. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62529. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62530. this.canUseWebAudio = true;
  62531. }
  62532. var audioElem = document.createElement('audio');
  62533. try {
  62534. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62535. this.isMP3supported = true;
  62536. }
  62537. }
  62538. catch (e) {
  62539. // protect error during capability check.
  62540. }
  62541. try {
  62542. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62543. this.isOGGsupported = true;
  62544. }
  62545. }
  62546. catch (e) {
  62547. // protect error during capability check.
  62548. }
  62549. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62550. this._unlockiOSaudio();
  62551. }
  62552. else {
  62553. this.unlocked = true;
  62554. }
  62555. }
  62556. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62557. get: function () {
  62558. if (!this._audioContextInitialized) {
  62559. this._initializeAudioContext();
  62560. }
  62561. return this._audioContext;
  62562. },
  62563. enumerable: true,
  62564. configurable: true
  62565. });
  62566. AudioEngine.prototype._unlockiOSaudio = function () {
  62567. var _this = this;
  62568. var unlockaudio = function () {
  62569. if (!_this.audioContext) {
  62570. return;
  62571. }
  62572. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62573. var source = _this.audioContext.createBufferSource();
  62574. source.buffer = buffer;
  62575. source.connect(_this.audioContext.destination);
  62576. source.start(0);
  62577. setTimeout(function () {
  62578. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62579. _this.unlocked = true;
  62580. window.removeEventListener('touchend', unlockaudio, false);
  62581. if (_this.onAudioUnlocked) {
  62582. _this.onAudioUnlocked();
  62583. }
  62584. }
  62585. }, 0);
  62586. };
  62587. window.addEventListener('touchend', unlockaudio, false);
  62588. };
  62589. AudioEngine.prototype._initializeAudioContext = function () {
  62590. try {
  62591. if (this.canUseWebAudio) {
  62592. this._audioContext = new AudioContext();
  62593. // create a global volume gain node
  62594. this.masterGain = this._audioContext.createGain();
  62595. this.masterGain.gain.value = 1;
  62596. this.masterGain.connect(this._audioContext.destination);
  62597. this._audioContextInitialized = true;
  62598. }
  62599. }
  62600. catch (e) {
  62601. this.canUseWebAudio = false;
  62602. BABYLON.Tools.Error("Web Audio: " + e.message);
  62603. }
  62604. };
  62605. AudioEngine.prototype.dispose = function () {
  62606. if (this.canUseWebAudio && this._audioContextInitialized) {
  62607. if (this._connectedAnalyser && this._audioContext) {
  62608. this._connectedAnalyser.stopDebugCanvas();
  62609. this._connectedAnalyser.dispose();
  62610. this.masterGain.disconnect();
  62611. this.masterGain.connect(this._audioContext.destination);
  62612. this._connectedAnalyser = null;
  62613. }
  62614. this.masterGain.gain.value = 1;
  62615. }
  62616. this.WarnedWebAudioUnsupported = false;
  62617. };
  62618. AudioEngine.prototype.getGlobalVolume = function () {
  62619. if (this.canUseWebAudio && this._audioContextInitialized) {
  62620. return this.masterGain.gain.value;
  62621. }
  62622. else {
  62623. return -1;
  62624. }
  62625. };
  62626. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62627. if (this.canUseWebAudio && this._audioContextInitialized) {
  62628. this.masterGain.gain.value = newVolume;
  62629. }
  62630. };
  62631. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62632. if (this._connectedAnalyser) {
  62633. this._connectedAnalyser.stopDebugCanvas();
  62634. }
  62635. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62636. this._connectedAnalyser = analyser;
  62637. this.masterGain.disconnect();
  62638. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62639. }
  62640. };
  62641. return AudioEngine;
  62642. }());
  62643. BABYLON.AudioEngine = AudioEngine;
  62644. })(BABYLON || (BABYLON = {}));
  62645. //# sourceMappingURL=babylon.audioEngine.js.map
  62646. var BABYLON;
  62647. (function (BABYLON) {
  62648. var Sound = /** @class */ (function () {
  62649. /**
  62650. * Create a sound and attach it to a scene
  62651. * @param name Name of your sound
  62652. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62653. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62654. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62655. */
  62656. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62657. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62658. var _this = this;
  62659. this.autoplay = false;
  62660. this.loop = false;
  62661. this.useCustomAttenuation = false;
  62662. this.spatialSound = false;
  62663. this.refDistance = 1;
  62664. this.rolloffFactor = 1;
  62665. this.maxDistance = 100;
  62666. this.distanceModel = "linear";
  62667. this._panningModel = "equalpower";
  62668. this._playbackRate = 1;
  62669. this._streaming = false;
  62670. this._startTime = 0;
  62671. this._startOffset = 0;
  62672. this._position = BABYLON.Vector3.Zero();
  62673. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62674. this._volume = 1;
  62675. this._isReadyToPlay = false;
  62676. this.isPlaying = false;
  62677. this.isPaused = false;
  62678. this._isDirectional = false;
  62679. // Used if you'd like to create a directional sound.
  62680. // If not set, the sound will be omnidirectional
  62681. this._coneInnerAngle = 360;
  62682. this._coneOuterAngle = 360;
  62683. this._coneOuterGain = 0;
  62684. this._isOutputConnected = false;
  62685. this._urlType = "Unknown";
  62686. this.name = name;
  62687. this._scene = scene;
  62688. this._readyToPlayCallback = readyToPlayCallback;
  62689. // Default custom attenuation function is a linear attenuation
  62690. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62691. if (currentDistance < maxDistance) {
  62692. return currentVolume * (1 - currentDistance / maxDistance);
  62693. }
  62694. else {
  62695. return 0;
  62696. }
  62697. };
  62698. if (options) {
  62699. this.autoplay = options.autoplay || false;
  62700. this.loop = options.loop || false;
  62701. // if volume === 0, we need another way to check this option
  62702. if (options.volume !== undefined) {
  62703. this._volume = options.volume;
  62704. }
  62705. this.spatialSound = options.spatialSound || false;
  62706. this.maxDistance = options.maxDistance || 100;
  62707. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62708. this.rolloffFactor = options.rolloffFactor || 1;
  62709. this.refDistance = options.refDistance || 1;
  62710. this.distanceModel = options.distanceModel || "linear";
  62711. this._playbackRate = options.playbackRate || 1;
  62712. this._streaming = options.streaming || false;
  62713. }
  62714. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62715. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62716. this._soundGain.gain.value = this._volume;
  62717. this._inputAudioNode = this._soundGain;
  62718. this._ouputAudioNode = this._soundGain;
  62719. if (this.spatialSound) {
  62720. this._createSpatialParameters();
  62721. }
  62722. this._scene.mainSoundTrack.AddSound(this);
  62723. var validParameter = true;
  62724. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62725. if (urlOrArrayBuffer) {
  62726. try {
  62727. if (typeof (urlOrArrayBuffer) === "string")
  62728. this._urlType = "String";
  62729. if (Array.isArray(urlOrArrayBuffer))
  62730. this._urlType = "Array";
  62731. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62732. this._urlType = "ArrayBuffer";
  62733. var urls = [];
  62734. var codecSupportedFound = false;
  62735. switch (this._urlType) {
  62736. case "ArrayBuffer":
  62737. if (urlOrArrayBuffer.byteLength > 0) {
  62738. codecSupportedFound = true;
  62739. this._soundLoaded(urlOrArrayBuffer);
  62740. }
  62741. break;
  62742. case "String":
  62743. urls.push(urlOrArrayBuffer);
  62744. case "Array":
  62745. if (urls.length === 0)
  62746. urls = urlOrArrayBuffer;
  62747. // If we found a supported format, we load it immediately and stop the loop
  62748. for (var i = 0; i < urls.length; i++) {
  62749. var url = urls[i];
  62750. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62751. codecSupportedFound = true;
  62752. }
  62753. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62754. codecSupportedFound = true;
  62755. }
  62756. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62757. codecSupportedFound = true;
  62758. }
  62759. if (url.indexOf("blob:") !== -1) {
  62760. codecSupportedFound = true;
  62761. }
  62762. if (codecSupportedFound) {
  62763. // Loading sound using XHR2
  62764. if (!this._streaming) {
  62765. this._scene._loadFile(url, function (data) {
  62766. _this._soundLoaded(data);
  62767. }, undefined, true, true, function (exception) {
  62768. if (exception) {
  62769. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62770. }
  62771. BABYLON.Tools.Error("Sound creation aborted.");
  62772. _this._scene.mainSoundTrack.RemoveSound(_this);
  62773. });
  62774. }
  62775. // Streaming sound using HTML5 Audio tag
  62776. else {
  62777. this._htmlAudioElement = new Audio(url);
  62778. this._htmlAudioElement.controls = false;
  62779. this._htmlAudioElement.loop = this.loop;
  62780. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62781. this._htmlAudioElement.preload = "auto";
  62782. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62783. _this._isReadyToPlay = true;
  62784. if (_this.autoplay) {
  62785. _this.play();
  62786. }
  62787. if (_this._readyToPlayCallback) {
  62788. _this._readyToPlayCallback();
  62789. }
  62790. });
  62791. document.body.appendChild(this._htmlAudioElement);
  62792. }
  62793. break;
  62794. }
  62795. }
  62796. break;
  62797. default:
  62798. validParameter = false;
  62799. break;
  62800. }
  62801. if (!validParameter) {
  62802. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62803. }
  62804. else {
  62805. if (!codecSupportedFound) {
  62806. this._isReadyToPlay = true;
  62807. // Simulating a ready to play event to avoid breaking code path
  62808. if (this._readyToPlayCallback) {
  62809. window.setTimeout(function () {
  62810. if (_this._readyToPlayCallback) {
  62811. _this._readyToPlayCallback();
  62812. }
  62813. }, 1000);
  62814. }
  62815. }
  62816. }
  62817. }
  62818. catch (ex) {
  62819. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62820. this._scene.mainSoundTrack.RemoveSound(this);
  62821. }
  62822. }
  62823. }
  62824. else {
  62825. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62826. this._scene.mainSoundTrack.AddSound(this);
  62827. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62828. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62829. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62830. }
  62831. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62832. if (this._readyToPlayCallback) {
  62833. window.setTimeout(function () {
  62834. if (_this._readyToPlayCallback) {
  62835. _this._readyToPlayCallback();
  62836. }
  62837. }, 1000);
  62838. }
  62839. }
  62840. }
  62841. Sound.prototype.dispose = function () {
  62842. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62843. if (this.isPlaying) {
  62844. this.stop();
  62845. }
  62846. this._isReadyToPlay = false;
  62847. if (this.soundTrackId === -1) {
  62848. this._scene.mainSoundTrack.RemoveSound(this);
  62849. }
  62850. else {
  62851. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62852. }
  62853. if (this._soundGain) {
  62854. this._soundGain.disconnect();
  62855. this._soundGain = null;
  62856. }
  62857. if (this._soundPanner) {
  62858. this._soundPanner.disconnect();
  62859. this._soundPanner = null;
  62860. }
  62861. if (this._soundSource) {
  62862. this._soundSource.disconnect();
  62863. this._soundSource = null;
  62864. }
  62865. this._audioBuffer = null;
  62866. if (this._htmlAudioElement) {
  62867. this._htmlAudioElement.pause();
  62868. this._htmlAudioElement.src = "";
  62869. document.body.removeChild(this._htmlAudioElement);
  62870. }
  62871. if (this._connectedMesh && this._registerFunc) {
  62872. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62873. this._connectedMesh = null;
  62874. }
  62875. }
  62876. };
  62877. Sound.prototype.isReady = function () {
  62878. return this._isReadyToPlay;
  62879. };
  62880. Sound.prototype._soundLoaded = function (audioData) {
  62881. var _this = this;
  62882. if (!BABYLON.Engine.audioEngine.audioContext) {
  62883. return;
  62884. }
  62885. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62886. _this._audioBuffer = buffer;
  62887. _this._isReadyToPlay = true;
  62888. if (_this.autoplay) {
  62889. _this.play();
  62890. }
  62891. if (_this._readyToPlayCallback) {
  62892. _this._readyToPlayCallback();
  62893. }
  62894. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62895. };
  62896. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62897. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62898. this._audioBuffer = audioBuffer;
  62899. this._isReadyToPlay = true;
  62900. }
  62901. };
  62902. Sound.prototype.updateOptions = function (options) {
  62903. if (options) {
  62904. this.loop = options.loop || this.loop;
  62905. this.maxDistance = options.maxDistance || this.maxDistance;
  62906. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62907. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62908. this.refDistance = options.refDistance || this.refDistance;
  62909. this.distanceModel = options.distanceModel || this.distanceModel;
  62910. this._playbackRate = options.playbackRate || this._playbackRate;
  62911. this._updateSpatialParameters();
  62912. if (this.isPlaying) {
  62913. if (this._streaming) {
  62914. this._htmlAudioElement.playbackRate = this._playbackRate;
  62915. }
  62916. else {
  62917. if (this._soundSource) {
  62918. this._soundSource.playbackRate.value = this._playbackRate;
  62919. }
  62920. }
  62921. }
  62922. }
  62923. };
  62924. Sound.prototype._createSpatialParameters = function () {
  62925. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62926. if (this._scene.headphone) {
  62927. this._panningModel = "HRTF";
  62928. }
  62929. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62930. this._updateSpatialParameters();
  62931. this._soundPanner.connect(this._ouputAudioNode);
  62932. this._inputAudioNode = this._soundPanner;
  62933. }
  62934. };
  62935. Sound.prototype._updateSpatialParameters = function () {
  62936. if (this.spatialSound && this._soundPanner) {
  62937. if (this.useCustomAttenuation) {
  62938. // Tricks to disable in a way embedded Web Audio attenuation
  62939. this._soundPanner.distanceModel = "linear";
  62940. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62941. this._soundPanner.refDistance = 1;
  62942. this._soundPanner.rolloffFactor = 1;
  62943. this._soundPanner.panningModel = this._panningModel;
  62944. }
  62945. else {
  62946. this._soundPanner.distanceModel = this.distanceModel;
  62947. this._soundPanner.maxDistance = this.maxDistance;
  62948. this._soundPanner.refDistance = this.refDistance;
  62949. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62950. this._soundPanner.panningModel = this._panningModel;
  62951. }
  62952. }
  62953. };
  62954. Sound.prototype.switchPanningModelToHRTF = function () {
  62955. this._panningModel = "HRTF";
  62956. this._switchPanningModel();
  62957. };
  62958. Sound.prototype.switchPanningModelToEqualPower = function () {
  62959. this._panningModel = "equalpower";
  62960. this._switchPanningModel();
  62961. };
  62962. Sound.prototype._switchPanningModel = function () {
  62963. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62964. this._soundPanner.panningModel = this._panningModel;
  62965. }
  62966. };
  62967. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62968. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62969. if (this._isOutputConnected) {
  62970. this._ouputAudioNode.disconnect();
  62971. }
  62972. this._ouputAudioNode.connect(soundTrackAudioNode);
  62973. this._isOutputConnected = true;
  62974. }
  62975. };
  62976. /**
  62977. * Transform this sound into a directional source
  62978. * @param coneInnerAngle Size of the inner cone in degree
  62979. * @param coneOuterAngle Size of the outer cone in degree
  62980. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62981. */
  62982. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62983. if (coneOuterAngle < coneInnerAngle) {
  62984. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62985. return;
  62986. }
  62987. this._coneInnerAngle = coneInnerAngle;
  62988. this._coneOuterAngle = coneOuterAngle;
  62989. this._coneOuterGain = coneOuterGain;
  62990. this._isDirectional = true;
  62991. if (this.isPlaying && this.loop) {
  62992. this.stop();
  62993. this.play();
  62994. }
  62995. };
  62996. Sound.prototype.setPosition = function (newPosition) {
  62997. this._position = newPosition;
  62998. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62999. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63000. }
  63001. };
  63002. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  63003. this._localDirection = newLocalDirection;
  63004. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  63005. this._updateDirection();
  63006. }
  63007. };
  63008. Sound.prototype._updateDirection = function () {
  63009. if (!this._connectedMesh || !this._soundPanner) {
  63010. return;
  63011. }
  63012. var mat = this._connectedMesh.getWorldMatrix();
  63013. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  63014. direction.normalize();
  63015. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  63016. };
  63017. Sound.prototype.updateDistanceFromListener = function () {
  63018. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  63019. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  63020. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  63021. }
  63022. };
  63023. Sound.prototype.setAttenuationFunction = function (callback) {
  63024. this._customAttenuationFunction = callback;
  63025. };
  63026. /**
  63027. * Play the sound
  63028. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  63029. * @param offset (optional) Start the sound setting it at a specific time
  63030. */
  63031. Sound.prototype.play = function (time, offset) {
  63032. var _this = this;
  63033. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  63034. try {
  63035. if (this._startOffset < 0) {
  63036. time = -this._startOffset;
  63037. this._startOffset = 0;
  63038. }
  63039. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63040. if (!this._soundSource || !this._streamingSource) {
  63041. if (this.spatialSound && this._soundPanner) {
  63042. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63043. if (this._isDirectional) {
  63044. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  63045. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  63046. this._soundPanner.coneOuterGain = this._coneOuterGain;
  63047. if (this._connectedMesh) {
  63048. this._updateDirection();
  63049. }
  63050. else {
  63051. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  63052. }
  63053. }
  63054. }
  63055. }
  63056. if (this._streaming) {
  63057. if (!this._streamingSource) {
  63058. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63059. this._htmlAudioElement.onended = function () { _this._onended(); };
  63060. this._htmlAudioElement.playbackRate = this._playbackRate;
  63061. }
  63062. this._streamingSource.disconnect();
  63063. this._streamingSource.connect(this._inputAudioNode);
  63064. this._htmlAudioElement.play();
  63065. }
  63066. else {
  63067. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63068. this._soundSource.buffer = this._audioBuffer;
  63069. this._soundSource.connect(this._inputAudioNode);
  63070. this._soundSource.loop = this.loop;
  63071. this._soundSource.playbackRate.value = this._playbackRate;
  63072. this._soundSource.onended = function () { _this._onended(); };
  63073. if (this._soundSource.buffer) {
  63074. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63075. }
  63076. }
  63077. this._startTime = startTime;
  63078. this.isPlaying = true;
  63079. this.isPaused = false;
  63080. }
  63081. catch (ex) {
  63082. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63083. }
  63084. }
  63085. };
  63086. Sound.prototype._onended = function () {
  63087. this.isPlaying = false;
  63088. if (this.onended) {
  63089. this.onended();
  63090. }
  63091. };
  63092. /**
  63093. * Stop the sound
  63094. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63095. */
  63096. Sound.prototype.stop = function (time) {
  63097. if (this.isPlaying) {
  63098. if (this._streaming) {
  63099. this._htmlAudioElement.pause();
  63100. // Test needed for Firefox or it will generate an Invalid State Error
  63101. if (this._htmlAudioElement.currentTime > 0) {
  63102. this._htmlAudioElement.currentTime = 0;
  63103. }
  63104. }
  63105. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63106. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63107. this._soundSource.stop(stopTime);
  63108. this._soundSource.onended = function () { };
  63109. if (!this.isPaused) {
  63110. this._startOffset = 0;
  63111. }
  63112. }
  63113. this.isPlaying = false;
  63114. }
  63115. };
  63116. Sound.prototype.pause = function () {
  63117. if (this.isPlaying) {
  63118. this.isPaused = true;
  63119. if (this._streaming) {
  63120. this._htmlAudioElement.pause();
  63121. }
  63122. else if (BABYLON.Engine.audioEngine.audioContext) {
  63123. this.stop(0);
  63124. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63125. }
  63126. }
  63127. };
  63128. Sound.prototype.setVolume = function (newVolume, time) {
  63129. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63130. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63131. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63132. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63133. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63134. }
  63135. else {
  63136. this._soundGain.gain.value = newVolume;
  63137. }
  63138. }
  63139. this._volume = newVolume;
  63140. };
  63141. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63142. this._playbackRate = newPlaybackRate;
  63143. if (this.isPlaying) {
  63144. if (this._streaming) {
  63145. this._htmlAudioElement.playbackRate = this._playbackRate;
  63146. }
  63147. else if (this._soundSource) {
  63148. this._soundSource.playbackRate.value = this._playbackRate;
  63149. }
  63150. }
  63151. };
  63152. Sound.prototype.getVolume = function () {
  63153. return this._volume;
  63154. };
  63155. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63156. var _this = this;
  63157. if (this._connectedMesh && this._registerFunc) {
  63158. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63159. this._registerFunc = null;
  63160. }
  63161. this._connectedMesh = meshToConnectTo;
  63162. if (!this.spatialSound) {
  63163. this.spatialSound = true;
  63164. this._createSpatialParameters();
  63165. if (this.isPlaying && this.loop) {
  63166. this.stop();
  63167. this.play();
  63168. }
  63169. }
  63170. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63171. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63172. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63173. };
  63174. Sound.prototype.detachFromMesh = function () {
  63175. if (this._connectedMesh && this._registerFunc) {
  63176. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63177. this._registerFunc = null;
  63178. this._connectedMesh = null;
  63179. }
  63180. };
  63181. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63182. if (!node.getBoundingInfo) {
  63183. return;
  63184. }
  63185. var mesh = node;
  63186. var boundingInfo = mesh.getBoundingInfo();
  63187. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63188. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63189. this._updateDirection();
  63190. }
  63191. };
  63192. Sound.prototype.clone = function () {
  63193. var _this = this;
  63194. if (!this._streaming) {
  63195. var setBufferAndRun = function () {
  63196. if (_this._isReadyToPlay) {
  63197. clonedSound._audioBuffer = _this.getAudioBuffer();
  63198. clonedSound._isReadyToPlay = true;
  63199. if (clonedSound.autoplay) {
  63200. clonedSound.play();
  63201. }
  63202. }
  63203. else {
  63204. window.setTimeout(setBufferAndRun, 300);
  63205. }
  63206. };
  63207. var currentOptions = {
  63208. autoplay: this.autoplay, loop: this.loop,
  63209. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63210. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63211. refDistance: this.refDistance, distanceModel: this.distanceModel
  63212. };
  63213. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63214. if (this.useCustomAttenuation) {
  63215. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63216. }
  63217. clonedSound.setPosition(this._position);
  63218. clonedSound.setPlaybackRate(this._playbackRate);
  63219. setBufferAndRun();
  63220. return clonedSound;
  63221. }
  63222. // Can't clone a streaming sound
  63223. else {
  63224. return null;
  63225. }
  63226. };
  63227. Sound.prototype.getAudioBuffer = function () {
  63228. return this._audioBuffer;
  63229. };
  63230. Sound.prototype.serialize = function () {
  63231. var serializationObject = {
  63232. name: this.name,
  63233. url: this.name,
  63234. autoplay: this.autoplay,
  63235. loop: this.loop,
  63236. volume: this._volume,
  63237. spatialSound: this.spatialSound,
  63238. maxDistance: this.maxDistance,
  63239. rolloffFactor: this.rolloffFactor,
  63240. refDistance: this.refDistance,
  63241. distanceModel: this.distanceModel,
  63242. playbackRate: this._playbackRate,
  63243. panningModel: this._panningModel,
  63244. soundTrackId: this.soundTrackId
  63245. };
  63246. if (this.spatialSound) {
  63247. if (this._connectedMesh)
  63248. serializationObject.connectedMeshId = this._connectedMesh.id;
  63249. serializationObject.position = this._position.asArray();
  63250. serializationObject.refDistance = this.refDistance;
  63251. serializationObject.distanceModel = this.distanceModel;
  63252. serializationObject.isDirectional = this._isDirectional;
  63253. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63254. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63255. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63256. serializationObject.coneOuterGain = this._coneOuterGain;
  63257. }
  63258. return serializationObject;
  63259. };
  63260. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63261. var soundName = parsedSound.name;
  63262. var soundUrl;
  63263. if (parsedSound.url) {
  63264. soundUrl = rootUrl + parsedSound.url;
  63265. }
  63266. else {
  63267. soundUrl = rootUrl + soundName;
  63268. }
  63269. var options = {
  63270. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63271. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63272. rolloffFactor: parsedSound.rolloffFactor,
  63273. refDistance: parsedSound.refDistance,
  63274. distanceModel: parsedSound.distanceModel,
  63275. playbackRate: parsedSound.playbackRate
  63276. };
  63277. var newSound;
  63278. if (!sourceSound) {
  63279. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63280. scene._addPendingData(newSound);
  63281. }
  63282. else {
  63283. var setBufferAndRun = function () {
  63284. if (sourceSound._isReadyToPlay) {
  63285. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63286. newSound._isReadyToPlay = true;
  63287. if (newSound.autoplay) {
  63288. newSound.play();
  63289. }
  63290. }
  63291. else {
  63292. window.setTimeout(setBufferAndRun, 300);
  63293. }
  63294. };
  63295. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63296. setBufferAndRun();
  63297. }
  63298. if (parsedSound.position) {
  63299. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63300. newSound.setPosition(soundPosition);
  63301. }
  63302. if (parsedSound.isDirectional) {
  63303. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63304. if (parsedSound.localDirectionToMesh) {
  63305. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63306. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63307. }
  63308. }
  63309. if (parsedSound.connectedMeshId) {
  63310. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63311. if (connectedMesh) {
  63312. newSound.attachToMesh(connectedMesh);
  63313. }
  63314. }
  63315. return newSound;
  63316. };
  63317. return Sound;
  63318. }());
  63319. BABYLON.Sound = Sound;
  63320. })(BABYLON || (BABYLON = {}));
  63321. //# sourceMappingURL=babylon.sound.js.map
  63322. var BABYLON;
  63323. (function (BABYLON) {
  63324. var SoundTrack = /** @class */ (function () {
  63325. function SoundTrack(scene, options) {
  63326. this.id = -1;
  63327. this._isMainTrack = false;
  63328. this._isInitialized = false;
  63329. this._scene = scene;
  63330. this.soundCollection = new Array();
  63331. this._options = options;
  63332. if (!this._isMainTrack) {
  63333. this._scene.soundTracks.push(this);
  63334. this.id = this._scene.soundTracks.length - 1;
  63335. }
  63336. }
  63337. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63338. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63339. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63340. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63341. if (this._options) {
  63342. if (this._options.volume) {
  63343. this._outputAudioNode.gain.value = this._options.volume;
  63344. }
  63345. if (this._options.mainTrack) {
  63346. this._isMainTrack = this._options.mainTrack;
  63347. }
  63348. }
  63349. this._isInitialized = true;
  63350. }
  63351. };
  63352. SoundTrack.prototype.dispose = function () {
  63353. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63354. if (this._connectedAnalyser) {
  63355. this._connectedAnalyser.stopDebugCanvas();
  63356. }
  63357. while (this.soundCollection.length) {
  63358. this.soundCollection[0].dispose();
  63359. }
  63360. if (this._outputAudioNode) {
  63361. this._outputAudioNode.disconnect();
  63362. }
  63363. this._outputAudioNode = null;
  63364. }
  63365. };
  63366. SoundTrack.prototype.AddSound = function (sound) {
  63367. if (!this._isInitialized) {
  63368. this._initializeSoundTrackAudioGraph();
  63369. }
  63370. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63371. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63372. }
  63373. if (sound.soundTrackId) {
  63374. if (sound.soundTrackId === -1) {
  63375. this._scene.mainSoundTrack.RemoveSound(sound);
  63376. }
  63377. else {
  63378. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63379. }
  63380. }
  63381. this.soundCollection.push(sound);
  63382. sound.soundTrackId = this.id;
  63383. };
  63384. SoundTrack.prototype.RemoveSound = function (sound) {
  63385. var index = this.soundCollection.indexOf(sound);
  63386. if (index !== -1) {
  63387. this.soundCollection.splice(index, 1);
  63388. }
  63389. };
  63390. SoundTrack.prototype.setVolume = function (newVolume) {
  63391. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63392. this._outputAudioNode.gain.value = newVolume;
  63393. }
  63394. };
  63395. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63396. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63397. for (var i = 0; i < this.soundCollection.length; i++) {
  63398. this.soundCollection[i].switchPanningModelToHRTF();
  63399. }
  63400. }
  63401. };
  63402. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63403. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63404. for (var i = 0; i < this.soundCollection.length; i++) {
  63405. this.soundCollection[i].switchPanningModelToEqualPower();
  63406. }
  63407. }
  63408. };
  63409. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63410. if (this._connectedAnalyser) {
  63411. this._connectedAnalyser.stopDebugCanvas();
  63412. }
  63413. this._connectedAnalyser = analyser;
  63414. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63415. this._outputAudioNode.disconnect();
  63416. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63417. }
  63418. };
  63419. return SoundTrack;
  63420. }());
  63421. BABYLON.SoundTrack = SoundTrack;
  63422. })(BABYLON || (BABYLON = {}));
  63423. //# sourceMappingURL=babylon.soundtrack.js.map
  63424. var BABYLON;
  63425. (function (BABYLON) {
  63426. /**
  63427. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63428. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63429. */
  63430. var Analyser = /** @class */ (function () {
  63431. /**
  63432. * Creates a new analyser
  63433. * @param scene defines hosting scene
  63434. */
  63435. function Analyser(scene) {
  63436. /**
  63437. * Gets or sets the smoothing
  63438. * @ignorenaming
  63439. */
  63440. this.SMOOTHING = 0.75;
  63441. /**
  63442. * Gets or sets the FFT table size
  63443. * @ignorenaming
  63444. */
  63445. this.FFT_SIZE = 512;
  63446. /**
  63447. * Gets or sets the bar graph amplitude
  63448. * @ignorenaming
  63449. */
  63450. this.BARGRAPHAMPLITUDE = 256;
  63451. /**
  63452. * Gets or sets the position of the debug canvas
  63453. * @ignorenaming
  63454. */
  63455. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63456. /**
  63457. * Gets or sets the debug canvas size
  63458. * @ignorenaming
  63459. */
  63460. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63461. this._scene = scene;
  63462. this._audioEngine = BABYLON.Engine.audioEngine;
  63463. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63464. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63465. this._webAudioAnalyser.minDecibels = -140;
  63466. this._webAudioAnalyser.maxDecibels = 0;
  63467. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63468. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63469. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63470. }
  63471. }
  63472. /**
  63473. * Get the number of data values you will have to play with for the visualization
  63474. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63475. * @returns a number
  63476. */
  63477. Analyser.prototype.getFrequencyBinCount = function () {
  63478. if (this._audioEngine.canUseWebAudio) {
  63479. return this._webAudioAnalyser.frequencyBinCount;
  63480. }
  63481. else {
  63482. return 0;
  63483. }
  63484. };
  63485. /**
  63486. * Gets the current frequency data as a byte array
  63487. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63488. * @returns a Uint8Array
  63489. */
  63490. Analyser.prototype.getByteFrequencyData = function () {
  63491. if (this._audioEngine.canUseWebAudio) {
  63492. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63493. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63494. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63495. }
  63496. return this._byteFreqs;
  63497. };
  63498. /**
  63499. * Gets the current waveform as a byte array
  63500. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63501. * @returns a Uint8Array
  63502. */
  63503. Analyser.prototype.getByteTimeDomainData = function () {
  63504. if (this._audioEngine.canUseWebAudio) {
  63505. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63506. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63507. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63508. }
  63509. return this._byteTime;
  63510. };
  63511. /**
  63512. * Gets the current frequency data as a float array
  63513. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63514. * @returns a Float32Array
  63515. */
  63516. Analyser.prototype.getFloatFrequencyData = function () {
  63517. if (this._audioEngine.canUseWebAudio) {
  63518. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63519. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63520. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63521. }
  63522. return this._floatFreqs;
  63523. };
  63524. /**
  63525. * Renders the debug canvas
  63526. */
  63527. Analyser.prototype.drawDebugCanvas = function () {
  63528. var _this = this;
  63529. if (this._audioEngine.canUseWebAudio) {
  63530. if (!this._debugCanvas) {
  63531. this._debugCanvas = document.createElement("canvas");
  63532. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63533. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63534. this._debugCanvas.style.position = "absolute";
  63535. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63536. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63537. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63538. document.body.appendChild(this._debugCanvas);
  63539. this._registerFunc = function () {
  63540. _this.drawDebugCanvas();
  63541. };
  63542. this._scene.registerBeforeRender(this._registerFunc);
  63543. }
  63544. if (this._registerFunc && this._debugCanvasContext) {
  63545. var workingArray = this.getByteFrequencyData();
  63546. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63547. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63548. // Draw the frequency domain chart.
  63549. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63550. var value = workingArray[i];
  63551. var percent = value / this.BARGRAPHAMPLITUDE;
  63552. var height = this.DEBUGCANVASSIZE.height * percent;
  63553. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63554. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63555. var hue = i / this.getFrequencyBinCount() * 360;
  63556. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63557. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63558. }
  63559. }
  63560. }
  63561. };
  63562. /**
  63563. * Stops rendering the debug canvas and removes it
  63564. */
  63565. Analyser.prototype.stopDebugCanvas = function () {
  63566. if (this._debugCanvas) {
  63567. if (this._registerFunc) {
  63568. this._scene.unregisterBeforeRender(this._registerFunc);
  63569. this._registerFunc = null;
  63570. }
  63571. document.body.removeChild(this._debugCanvas);
  63572. this._debugCanvas = null;
  63573. this._debugCanvasContext = null;
  63574. }
  63575. };
  63576. /**
  63577. * Connects two audio nodes
  63578. * @param inputAudioNode defines first node to connect
  63579. * @param outputAudioNode defines second node to connect
  63580. */
  63581. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63582. if (this._audioEngine.canUseWebAudio) {
  63583. inputAudioNode.connect(this._webAudioAnalyser);
  63584. this._webAudioAnalyser.connect(outputAudioNode);
  63585. }
  63586. };
  63587. /**
  63588. * Releases all associated resources
  63589. */
  63590. Analyser.prototype.dispose = function () {
  63591. if (this._audioEngine.canUseWebAudio) {
  63592. this._webAudioAnalyser.disconnect();
  63593. }
  63594. };
  63595. return Analyser;
  63596. }());
  63597. BABYLON.Analyser = Analyser;
  63598. })(BABYLON || (BABYLON = {}));
  63599. //# sourceMappingURL=babylon.analyser.js.map
  63600. var BABYLON;
  63601. (function (BABYLON) {
  63602. var CubeTexture = /** @class */ (function (_super) {
  63603. __extends(CubeTexture, _super);
  63604. /**
  63605. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63606. * as prefiltered data.
  63607. * @param rootUrl defines the url of the texture or the root name of the six images
  63608. * @param scene defines the scene the texture is attached to
  63609. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63610. * @param noMipmap defines if mipmaps should be created or not
  63611. * @param files defines the six files to load for the different faces
  63612. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63613. * @param onError defines a callback triggered in case of error during load
  63614. * @param format defines the internal format to use for the texture once loaded
  63615. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63616. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63617. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63618. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63619. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63620. * @return the cube texture
  63621. */
  63622. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63623. if (extensions === void 0) { extensions = null; }
  63624. if (noMipmap === void 0) { noMipmap = false; }
  63625. if (files === void 0) { files = null; }
  63626. if (onLoad === void 0) { onLoad = null; }
  63627. if (onError === void 0) { onError = null; }
  63628. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63629. if (prefiltered === void 0) { prefiltered = false; }
  63630. if (forcedExtension === void 0) { forcedExtension = null; }
  63631. if (createPolynomials === void 0) { createPolynomials = false; }
  63632. if (lodScale === void 0) { lodScale = 0.8; }
  63633. if (lodOffset === void 0) { lodOffset = 0; }
  63634. var _this = _super.call(this, scene) || this;
  63635. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63636. /**
  63637. * Gets or sets the center of the bounding box associated with the cube texture
  63638. * It must define where the camera used to render the texture was set
  63639. */
  63640. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63641. _this._rotationY = 0;
  63642. /** @hidden */
  63643. _this._prefiltered = false;
  63644. _this.name = rootUrl;
  63645. _this.url = rootUrl;
  63646. _this._noMipmap = noMipmap;
  63647. _this.hasAlpha = false;
  63648. _this._format = format;
  63649. _this.isCube = true;
  63650. _this._textureMatrix = BABYLON.Matrix.Identity();
  63651. _this._createPolynomials = createPolynomials;
  63652. if (!rootUrl && !files) {
  63653. return _this;
  63654. }
  63655. var lastDot = rootUrl.lastIndexOf(".");
  63656. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63657. var isDDS = (extension === ".dds");
  63658. var isEnv = (extension === ".env");
  63659. if (isEnv) {
  63660. _this.gammaSpace = false;
  63661. _this._prefiltered = false;
  63662. }
  63663. else {
  63664. _this._prefiltered = prefiltered;
  63665. if (prefiltered) {
  63666. _this.gammaSpace = false;
  63667. }
  63668. }
  63669. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63670. if (!files) {
  63671. if (!isEnv && !isDDS && !extensions) {
  63672. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63673. }
  63674. files = [];
  63675. if (extensions) {
  63676. for (var index = 0; index < extensions.length; index++) {
  63677. files.push(rootUrl + extensions[index]);
  63678. }
  63679. }
  63680. }
  63681. _this._files = files;
  63682. if (!_this._texture) {
  63683. if (!scene.useDelayedTextureLoading) {
  63684. if (prefiltered) {
  63685. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63686. }
  63687. else {
  63688. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63689. }
  63690. }
  63691. else {
  63692. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63693. }
  63694. }
  63695. else if (onLoad) {
  63696. if (_this._texture.isReady) {
  63697. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63698. }
  63699. else {
  63700. _this._texture.onLoadedObservable.add(onLoad);
  63701. }
  63702. }
  63703. return _this;
  63704. }
  63705. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63706. get: function () {
  63707. return this._boundingBoxSize;
  63708. },
  63709. /**
  63710. * Gets or sets the size of the bounding box associated with the cube texture
  63711. * When defined, the cubemap will switch to local mode
  63712. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63713. * @example https://www.babylonjs-playground.com/#RNASML
  63714. */
  63715. set: function (value) {
  63716. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63717. return;
  63718. }
  63719. this._boundingBoxSize = value;
  63720. var scene = this.getScene();
  63721. if (scene) {
  63722. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63723. }
  63724. },
  63725. enumerable: true,
  63726. configurable: true
  63727. });
  63728. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63729. /**
  63730. * Gets texture matrix rotation angle around Y axis radians.
  63731. */
  63732. get: function () {
  63733. return this._rotationY;
  63734. },
  63735. /**
  63736. * Sets texture matrix rotation angle around Y axis in radians.
  63737. */
  63738. set: function (value) {
  63739. this._rotationY = value;
  63740. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63741. },
  63742. enumerable: true,
  63743. configurable: true
  63744. });
  63745. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63746. var rootUrlKey = "";
  63747. files.forEach(function (url) { return rootUrlKey += url; });
  63748. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63749. };
  63750. /**
  63751. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63752. * @param url defines the url of the prefiltered texture
  63753. * @param scene defines the scene the texture is attached to
  63754. * @param forcedExtension defines the extension of the file if different from the url
  63755. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63756. * @return the prefiltered texture
  63757. */
  63758. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63759. if (forcedExtension === void 0) { forcedExtension = null; }
  63760. if (createPolynomials === void 0) { createPolynomials = true; }
  63761. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63762. };
  63763. // Methods
  63764. CubeTexture.prototype.delayLoad = function () {
  63765. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63766. return;
  63767. }
  63768. var scene = this.getScene();
  63769. if (!scene) {
  63770. return;
  63771. }
  63772. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63773. this._texture = this._getFromCache(this.url, this._noMipmap);
  63774. if (!this._texture) {
  63775. if (this._prefiltered) {
  63776. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63777. }
  63778. else {
  63779. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63780. }
  63781. }
  63782. };
  63783. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63784. return this._textureMatrix;
  63785. };
  63786. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63787. this._textureMatrix = value;
  63788. };
  63789. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63790. var texture = BABYLON.SerializationHelper.Parse(function () {
  63791. var prefiltered = false;
  63792. if (parsedTexture.prefiltered) {
  63793. prefiltered = parsedTexture.prefiltered;
  63794. }
  63795. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63796. }, parsedTexture, scene);
  63797. // Local Cubemaps
  63798. if (parsedTexture.boundingBoxPosition) {
  63799. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63800. }
  63801. if (parsedTexture.boundingBoxSize) {
  63802. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63803. }
  63804. // Animations
  63805. if (parsedTexture.animations) {
  63806. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63807. var parsedAnimation = parsedTexture.animations[animationIndex];
  63808. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63809. }
  63810. }
  63811. return texture;
  63812. };
  63813. CubeTexture.prototype.clone = function () {
  63814. var _this = this;
  63815. return BABYLON.SerializationHelper.Clone(function () {
  63816. var scene = _this.getScene();
  63817. if (!scene) {
  63818. return _this;
  63819. }
  63820. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63821. }, this);
  63822. };
  63823. __decorate([
  63824. BABYLON.serialize("rotationY")
  63825. ], CubeTexture.prototype, "_rotationY", void 0);
  63826. return CubeTexture;
  63827. }(BABYLON.BaseTexture));
  63828. BABYLON.CubeTexture = CubeTexture;
  63829. })(BABYLON || (BABYLON = {}));
  63830. //# sourceMappingURL=babylon.cubeTexture.js.map
  63831. var BABYLON;
  63832. (function (BABYLON) {
  63833. var RenderTargetTexture = /** @class */ (function (_super) {
  63834. __extends(RenderTargetTexture, _super);
  63835. /**
  63836. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63837. * or used a shadow, depth texture...
  63838. * @param name The friendly name of the texture
  63839. * @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)
  63840. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63841. * @param generateMipMaps True if mip maps need to be generated after render.
  63842. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63843. * @param type The type of the buffer in the RTT (int, half float, float...)
  63844. * @param isCube True if a cube texture needs to be created
  63845. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63846. * @param generateDepthBuffer True to generate a depth buffer
  63847. * @param generateStencilBuffer True to generate a stencil buffer
  63848. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63849. */
  63850. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63851. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63852. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63853. if (isCube === void 0) { isCube = false; }
  63854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63855. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63856. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63857. if (isMulti === void 0) { isMulti = false; }
  63858. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63859. _this.isCube = isCube;
  63860. /**
  63861. * Use this list to define the list of mesh you want to render.
  63862. */
  63863. _this.renderList = new Array();
  63864. _this.renderParticles = true;
  63865. _this.renderSprites = false;
  63866. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63867. _this.ignoreCameraViewport = false;
  63868. // Events
  63869. /**
  63870. * An event triggered when the texture is unbind.
  63871. */
  63872. _this.onBeforeBindObservable = new BABYLON.Observable();
  63873. /**
  63874. * An event triggered when the texture is unbind.
  63875. */
  63876. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63877. /**
  63878. * An event triggered before rendering the texture
  63879. */
  63880. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63881. /**
  63882. * An event triggered after rendering the texture
  63883. */
  63884. _this.onAfterRenderObservable = new BABYLON.Observable();
  63885. /**
  63886. * An event triggered after the texture clear
  63887. */
  63888. _this.onClearObservable = new BABYLON.Observable();
  63889. _this._currentRefreshId = -1;
  63890. _this._refreshRate = 1;
  63891. _this._samples = 1;
  63892. /**
  63893. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63894. * It must define where the camera used to render the texture is set
  63895. */
  63896. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63897. scene = _this.getScene();
  63898. if (!scene) {
  63899. return _this;
  63900. }
  63901. _this._engine = scene.getEngine();
  63902. _this.name = name;
  63903. _this.isRenderTarget = true;
  63904. _this._initialSizeParameter = size;
  63905. _this._processSizeParameter(size);
  63906. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63907. });
  63908. _this._generateMipMaps = generateMipMaps ? true : false;
  63909. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63910. // Rendering groups
  63911. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63912. if (isMulti) {
  63913. return _this;
  63914. }
  63915. _this._renderTargetOptions = {
  63916. generateMipMaps: generateMipMaps,
  63917. type: type,
  63918. samplingMode: samplingMode,
  63919. generateDepthBuffer: generateDepthBuffer,
  63920. generateStencilBuffer: generateStencilBuffer
  63921. };
  63922. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63923. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63924. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63925. }
  63926. if (isCube) {
  63927. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63928. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63929. _this._textureMatrix = BABYLON.Matrix.Identity();
  63930. }
  63931. else {
  63932. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63933. }
  63934. return _this;
  63935. }
  63936. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63937. get: function () {
  63938. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63939. },
  63940. enumerable: true,
  63941. configurable: true
  63942. });
  63943. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63944. get: function () {
  63945. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63946. },
  63947. enumerable: true,
  63948. configurable: true
  63949. });
  63950. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63951. get: function () {
  63952. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63953. },
  63954. enumerable: true,
  63955. configurable: true
  63956. });
  63957. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63958. set: function (callback) {
  63959. if (this._onAfterUnbindObserver) {
  63960. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63961. }
  63962. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63963. },
  63964. enumerable: true,
  63965. configurable: true
  63966. });
  63967. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63968. set: function (callback) {
  63969. if (this._onBeforeRenderObserver) {
  63970. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63971. }
  63972. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63973. },
  63974. enumerable: true,
  63975. configurable: true
  63976. });
  63977. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63978. set: function (callback) {
  63979. if (this._onAfterRenderObserver) {
  63980. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63981. }
  63982. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63983. },
  63984. enumerable: true,
  63985. configurable: true
  63986. });
  63987. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63988. set: function (callback) {
  63989. if (this._onClearObserver) {
  63990. this.onClearObservable.remove(this._onClearObserver);
  63991. }
  63992. this._onClearObserver = this.onClearObservable.add(callback);
  63993. },
  63994. enumerable: true,
  63995. configurable: true
  63996. });
  63997. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63998. get: function () {
  63999. return this._renderTargetOptions;
  64000. },
  64001. enumerable: true,
  64002. configurable: true
  64003. });
  64004. RenderTargetTexture.prototype._onRatioRescale = function () {
  64005. if (this._sizeRatio) {
  64006. this.resize(this._initialSizeParameter);
  64007. }
  64008. };
  64009. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64010. get: function () {
  64011. return this._boundingBoxSize;
  64012. },
  64013. /**
  64014. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64015. * When defined, the cubemap will switch to local mode
  64016. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64017. * @example https://www.babylonjs-playground.com/#RNASML
  64018. */
  64019. set: function (value) {
  64020. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64021. return;
  64022. }
  64023. this._boundingBoxSize = value;
  64024. var scene = this.getScene();
  64025. if (scene) {
  64026. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64027. }
  64028. },
  64029. enumerable: true,
  64030. configurable: true
  64031. });
  64032. /**
  64033. * Creates a depth stencil texture.
  64034. * This is only available in WebGL 2 or with the depth texture extension available.
  64035. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64036. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64037. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64038. */
  64039. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64040. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64041. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64042. if (generateStencil === void 0) { generateStencil = false; }
  64043. if (!this.getScene()) {
  64044. return;
  64045. }
  64046. var engine = this.getScene().getEngine();
  64047. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64048. bilinearFiltering: bilinearFiltering,
  64049. comparisonFunction: comparisonFunction,
  64050. generateStencil: generateStencil,
  64051. isCube: this.isCube
  64052. });
  64053. engine.setFrameBufferDepthStencilTexture(this);
  64054. };
  64055. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64056. if (size.ratio) {
  64057. this._sizeRatio = size.ratio;
  64058. this._size = {
  64059. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64060. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64061. };
  64062. }
  64063. else {
  64064. this._size = size;
  64065. }
  64066. };
  64067. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64068. get: function () {
  64069. return this._samples;
  64070. },
  64071. set: function (value) {
  64072. if (this._samples === value) {
  64073. return;
  64074. }
  64075. var scene = this.getScene();
  64076. if (!scene) {
  64077. return;
  64078. }
  64079. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64080. },
  64081. enumerable: true,
  64082. configurable: true
  64083. });
  64084. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64085. this._currentRefreshId = -1;
  64086. };
  64087. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64088. get: function () {
  64089. return this._refreshRate;
  64090. },
  64091. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64092. set: function (value) {
  64093. this._refreshRate = value;
  64094. this.resetRefreshCounter();
  64095. },
  64096. enumerable: true,
  64097. configurable: true
  64098. });
  64099. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64100. if (!this._postProcessManager) {
  64101. var scene = this.getScene();
  64102. if (!scene) {
  64103. return;
  64104. }
  64105. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64106. this._postProcesses = new Array();
  64107. }
  64108. this._postProcesses.push(postProcess);
  64109. this._postProcesses[0].autoClear = false;
  64110. };
  64111. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64112. if (!this._postProcesses) {
  64113. return;
  64114. }
  64115. if (dispose) {
  64116. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64117. var postProcess = _a[_i];
  64118. postProcess.dispose();
  64119. }
  64120. }
  64121. this._postProcesses = [];
  64122. };
  64123. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64124. if (!this._postProcesses) {
  64125. return;
  64126. }
  64127. var index = this._postProcesses.indexOf(postProcess);
  64128. if (index === -1) {
  64129. return;
  64130. }
  64131. this._postProcesses.splice(index, 1);
  64132. if (this._postProcesses.length > 0) {
  64133. this._postProcesses[0].autoClear = false;
  64134. }
  64135. };
  64136. RenderTargetTexture.prototype._shouldRender = function () {
  64137. if (this._currentRefreshId === -1) { // At least render once
  64138. this._currentRefreshId = 1;
  64139. return true;
  64140. }
  64141. if (this.refreshRate === this._currentRefreshId) {
  64142. this._currentRefreshId = 1;
  64143. return true;
  64144. }
  64145. this._currentRefreshId++;
  64146. return false;
  64147. };
  64148. RenderTargetTexture.prototype.getRenderSize = function () {
  64149. if (this._size.width) {
  64150. return this._size.width;
  64151. }
  64152. return this._size;
  64153. };
  64154. RenderTargetTexture.prototype.getRenderWidth = function () {
  64155. if (this._size.width) {
  64156. return this._size.width;
  64157. }
  64158. return this._size;
  64159. };
  64160. RenderTargetTexture.prototype.getRenderHeight = function () {
  64161. if (this._size.width) {
  64162. return this._size.height;
  64163. }
  64164. return this._size;
  64165. };
  64166. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64167. get: function () {
  64168. return true;
  64169. },
  64170. enumerable: true,
  64171. configurable: true
  64172. });
  64173. RenderTargetTexture.prototype.scale = function (ratio) {
  64174. var newSize = this.getRenderSize() * ratio;
  64175. this.resize(newSize);
  64176. };
  64177. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64178. if (this.isCube) {
  64179. return this._textureMatrix;
  64180. }
  64181. return _super.prototype.getReflectionTextureMatrix.call(this);
  64182. };
  64183. RenderTargetTexture.prototype.resize = function (size) {
  64184. this.releaseInternalTexture();
  64185. var scene = this.getScene();
  64186. if (!scene) {
  64187. return;
  64188. }
  64189. this._processSizeParameter(size);
  64190. if (this.isCube) {
  64191. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64192. }
  64193. else {
  64194. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64195. }
  64196. };
  64197. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64198. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64199. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64200. var scene = this.getScene();
  64201. if (!scene) {
  64202. return;
  64203. }
  64204. var engine = scene.getEngine();
  64205. if (this.useCameraPostProcesses !== undefined) {
  64206. useCameraPostProcess = this.useCameraPostProcesses;
  64207. }
  64208. if (this._waitingRenderList) {
  64209. this.renderList = [];
  64210. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64211. var id = this._waitingRenderList[index];
  64212. var mesh_1 = scene.getMeshByID(id);
  64213. if (mesh_1) {
  64214. this.renderList.push(mesh_1);
  64215. }
  64216. }
  64217. delete this._waitingRenderList;
  64218. }
  64219. // Is predicate defined?
  64220. if (this.renderListPredicate) {
  64221. if (this.renderList) {
  64222. this.renderList.splice(0); // Clear previous renderList
  64223. }
  64224. else {
  64225. this.renderList = [];
  64226. }
  64227. var scene = this.getScene();
  64228. if (!scene) {
  64229. return;
  64230. }
  64231. var sceneMeshes = scene.meshes;
  64232. for (var index = 0; index < sceneMeshes.length; index++) {
  64233. var mesh = sceneMeshes[index];
  64234. if (this.renderListPredicate(mesh)) {
  64235. this.renderList.push(mesh);
  64236. }
  64237. }
  64238. }
  64239. this.onBeforeBindObservable.notifyObservers(this);
  64240. // Set custom projection.
  64241. // Needs to be before binding to prevent changing the aspect ratio.
  64242. var camera;
  64243. if (this.activeCamera) {
  64244. camera = this.activeCamera;
  64245. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64246. if (this.activeCamera !== scene.activeCamera) {
  64247. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64248. }
  64249. }
  64250. else {
  64251. camera = scene.activeCamera;
  64252. if (camera) {
  64253. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64254. }
  64255. }
  64256. // Prepare renderingManager
  64257. this._renderingManager.reset();
  64258. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64259. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64260. var sceneRenderId = scene.getRenderId();
  64261. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64262. var mesh = currentRenderList[meshIndex];
  64263. if (mesh) {
  64264. if (!mesh.isReady(this.refreshRate === 0)) {
  64265. this.resetRefreshCounter();
  64266. continue;
  64267. }
  64268. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64269. var isMasked = void 0;
  64270. if (!this.renderList && camera) {
  64271. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64272. }
  64273. else {
  64274. isMasked = false;
  64275. }
  64276. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64277. mesh._activate(sceneRenderId);
  64278. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64279. var subMesh = mesh.subMeshes[subIndex];
  64280. scene._activeIndices.addCount(subMesh.indexCount, false);
  64281. this._renderingManager.dispatch(subMesh, mesh);
  64282. }
  64283. }
  64284. }
  64285. }
  64286. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64287. var particleSystem = scene.particleSystems[particleIndex];
  64288. var emitter = particleSystem.emitter;
  64289. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64290. continue;
  64291. }
  64292. if (currentRenderList.indexOf(emitter) >= 0) {
  64293. this._renderingManager.dispatchParticles(particleSystem);
  64294. }
  64295. }
  64296. if (this.isCube) {
  64297. for (var face = 0; face < 6; face++) {
  64298. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64299. scene.incrementRenderId();
  64300. scene.resetCachedMaterial();
  64301. }
  64302. }
  64303. else {
  64304. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64305. }
  64306. this.onAfterUnbindObservable.notifyObservers(this);
  64307. if (scene.activeCamera) {
  64308. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64309. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64310. }
  64311. engine.setViewport(scene.activeCamera.viewport);
  64312. }
  64313. scene.resetCachedMaterial();
  64314. };
  64315. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64316. var minimum = 128;
  64317. var x = renderDimension * scale;
  64318. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64319. // Ensure we don't exceed the render dimension (while staying POT)
  64320. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64321. };
  64322. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64323. var _this = this;
  64324. if (!this._texture) {
  64325. return;
  64326. }
  64327. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64328. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64329. });
  64330. };
  64331. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64332. var scene = this.getScene();
  64333. if (!scene) {
  64334. return;
  64335. }
  64336. var engine = scene.getEngine();
  64337. if (!this._texture) {
  64338. return;
  64339. }
  64340. // Bind
  64341. if (this._postProcessManager) {
  64342. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64343. }
  64344. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64345. if (this._texture) {
  64346. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64347. }
  64348. }
  64349. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64350. // Clear
  64351. if (this.onClearObservable.hasObservers()) {
  64352. this.onClearObservable.notifyObservers(engine);
  64353. }
  64354. else {
  64355. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64356. }
  64357. if (!this._doNotChangeAspectRatio) {
  64358. scene.updateTransformMatrix(true);
  64359. }
  64360. // Render
  64361. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64362. if (this._postProcessManager) {
  64363. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64364. }
  64365. else if (useCameraPostProcess) {
  64366. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64367. }
  64368. if (!this._doNotChangeAspectRatio) {
  64369. scene.updateTransformMatrix(true);
  64370. }
  64371. // Dump ?
  64372. if (dumpForDebug) {
  64373. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64374. }
  64375. // Unbind
  64376. if (!this.isCube || faceIndex === 5) {
  64377. if (this.isCube) {
  64378. if (faceIndex === 5) {
  64379. engine.generateMipMapsForCubemap(this._texture);
  64380. }
  64381. }
  64382. this.unbindFrameBuffer(engine, faceIndex);
  64383. }
  64384. else {
  64385. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64386. }
  64387. };
  64388. /**
  64389. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64390. * This allowed control for front to back rendering or reversly depending of the special needs.
  64391. *
  64392. * @param renderingGroupId The rendering group id corresponding to its index
  64393. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64394. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64395. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64396. */
  64397. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64398. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64399. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64400. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64401. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64402. };
  64403. /**
  64404. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64405. *
  64406. * @param renderingGroupId The rendering group id corresponding to its index
  64407. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64408. */
  64409. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64410. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64411. };
  64412. RenderTargetTexture.prototype.clone = function () {
  64413. var textureSize = this.getSize();
  64414. 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);
  64415. // Base texture
  64416. newTexture.hasAlpha = this.hasAlpha;
  64417. newTexture.level = this.level;
  64418. // RenderTarget Texture
  64419. newTexture.coordinatesMode = this.coordinatesMode;
  64420. if (this.renderList) {
  64421. newTexture.renderList = this.renderList.slice(0);
  64422. }
  64423. return newTexture;
  64424. };
  64425. RenderTargetTexture.prototype.serialize = function () {
  64426. if (!this.name) {
  64427. return null;
  64428. }
  64429. var serializationObject = _super.prototype.serialize.call(this);
  64430. serializationObject.renderTargetSize = this.getRenderSize();
  64431. serializationObject.renderList = [];
  64432. if (this.renderList) {
  64433. for (var index = 0; index < this.renderList.length; index++) {
  64434. serializationObject.renderList.push(this.renderList[index].id);
  64435. }
  64436. }
  64437. return serializationObject;
  64438. };
  64439. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64440. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64441. var objBuffer = this.getInternalTexture();
  64442. var scene = this.getScene();
  64443. if (objBuffer && scene) {
  64444. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64445. }
  64446. };
  64447. RenderTargetTexture.prototype.dispose = function () {
  64448. if (this._postProcessManager) {
  64449. this._postProcessManager.dispose();
  64450. this._postProcessManager = null;
  64451. }
  64452. this.clearPostProcesses(true);
  64453. if (this._resizeObserver) {
  64454. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64455. this._resizeObserver = null;
  64456. }
  64457. this.renderList = null;
  64458. // Remove from custom render targets
  64459. var scene = this.getScene();
  64460. if (!scene) {
  64461. return;
  64462. }
  64463. var index = scene.customRenderTargets.indexOf(this);
  64464. if (index >= 0) {
  64465. scene.customRenderTargets.splice(index, 1);
  64466. }
  64467. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64468. var camera = _a[_i];
  64469. index = camera.customRenderTargets.indexOf(this);
  64470. if (index >= 0) {
  64471. camera.customRenderTargets.splice(index, 1);
  64472. }
  64473. }
  64474. _super.prototype.dispose.call(this);
  64475. };
  64476. RenderTargetTexture.prototype._rebuild = function () {
  64477. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64478. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64479. }
  64480. if (this._postProcessManager) {
  64481. this._postProcessManager._rebuild();
  64482. }
  64483. };
  64484. /**
  64485. * Clear the info related to rendering groups preventing retention point in material dispose.
  64486. */
  64487. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64488. if (this._renderingManager) {
  64489. this._renderingManager.freeRenderingGroups();
  64490. }
  64491. };
  64492. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64493. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64494. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64495. return RenderTargetTexture;
  64496. }(BABYLON.Texture));
  64497. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64498. })(BABYLON || (BABYLON = {}));
  64499. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64500. var BABYLON;
  64501. (function (BABYLON) {
  64502. ;
  64503. var MultiRenderTarget = /** @class */ (function (_super) {
  64504. __extends(MultiRenderTarget, _super);
  64505. function MultiRenderTarget(name, size, count, scene, options) {
  64506. var _this = this;
  64507. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64508. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64509. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64510. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64511. _this._engine = scene.getEngine();
  64512. if (!_this.isSupported) {
  64513. _this.dispose();
  64514. return;
  64515. }
  64516. var types = [];
  64517. var samplingModes = [];
  64518. for (var i = 0; i < count; i++) {
  64519. if (options && options.types && options.types[i] !== undefined) {
  64520. types.push(options.types[i]);
  64521. }
  64522. else {
  64523. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64524. }
  64525. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64526. samplingModes.push(options.samplingModes[i]);
  64527. }
  64528. else {
  64529. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64530. }
  64531. }
  64532. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64533. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64534. _this._size = size;
  64535. _this._multiRenderTargetOptions = {
  64536. samplingModes: samplingModes,
  64537. generateMipMaps: generateMipMaps,
  64538. generateDepthBuffer: generateDepthBuffer,
  64539. generateStencilBuffer: generateStencilBuffer,
  64540. generateDepthTexture: generateDepthTexture,
  64541. types: types,
  64542. textureCount: count
  64543. };
  64544. _this._createInternalTextures();
  64545. _this._createTextures();
  64546. return _this;
  64547. }
  64548. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64549. get: function () {
  64550. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64551. },
  64552. enumerable: true,
  64553. configurable: true
  64554. });
  64555. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64556. get: function () {
  64557. return this._textures;
  64558. },
  64559. enumerable: true,
  64560. configurable: true
  64561. });
  64562. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64563. get: function () {
  64564. return this._textures[this._textures.length - 1];
  64565. },
  64566. enumerable: true,
  64567. configurable: true
  64568. });
  64569. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64570. set: function (wrap) {
  64571. if (this._textures) {
  64572. for (var i = 0; i < this._textures.length; i++) {
  64573. this._textures[i].wrapU = wrap;
  64574. }
  64575. }
  64576. },
  64577. enumerable: true,
  64578. configurable: true
  64579. });
  64580. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64581. set: function (wrap) {
  64582. if (this._textures) {
  64583. for (var i = 0; i < this._textures.length; i++) {
  64584. this._textures[i].wrapV = wrap;
  64585. }
  64586. }
  64587. },
  64588. enumerable: true,
  64589. configurable: true
  64590. });
  64591. MultiRenderTarget.prototype._rebuild = function () {
  64592. this.releaseInternalTextures();
  64593. this._createInternalTextures();
  64594. for (var i = 0; i < this._internalTextures.length; i++) {
  64595. var texture = this._textures[i];
  64596. texture._texture = this._internalTextures[i];
  64597. }
  64598. // Keeps references to frame buffer and stencil/depth buffer
  64599. this._texture = this._internalTextures[0];
  64600. };
  64601. MultiRenderTarget.prototype._createInternalTextures = function () {
  64602. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64603. };
  64604. MultiRenderTarget.prototype._createTextures = function () {
  64605. this._textures = [];
  64606. for (var i = 0; i < this._internalTextures.length; i++) {
  64607. var texture = new BABYLON.Texture(null, this.getScene());
  64608. texture._texture = this._internalTextures[i];
  64609. this._textures.push(texture);
  64610. }
  64611. // Keeps references to frame buffer and stencil/depth buffer
  64612. this._texture = this._internalTextures[0];
  64613. };
  64614. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64615. get: function () {
  64616. return this._samples;
  64617. },
  64618. set: function (value) {
  64619. if (this._samples === value) {
  64620. return;
  64621. }
  64622. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64623. },
  64624. enumerable: true,
  64625. configurable: true
  64626. });
  64627. MultiRenderTarget.prototype.resize = function (size) {
  64628. this.releaseInternalTextures();
  64629. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64630. this._createInternalTextures();
  64631. };
  64632. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64633. var _this = this;
  64634. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64635. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64636. });
  64637. };
  64638. MultiRenderTarget.prototype.dispose = function () {
  64639. this.releaseInternalTextures();
  64640. _super.prototype.dispose.call(this);
  64641. };
  64642. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64643. if (!this._internalTextures) {
  64644. return;
  64645. }
  64646. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64647. if (this._internalTextures[i] !== undefined) {
  64648. this._internalTextures[i].dispose();
  64649. this._internalTextures.splice(i, 1);
  64650. }
  64651. }
  64652. };
  64653. return MultiRenderTarget;
  64654. }(BABYLON.RenderTargetTexture));
  64655. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64656. })(BABYLON || (BABYLON = {}));
  64657. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64658. var BABYLON;
  64659. (function (BABYLON) {
  64660. var MirrorTexture = /** @class */ (function (_super) {
  64661. __extends(MirrorTexture, _super);
  64662. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64663. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64665. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64666. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64667. _this.scene = scene;
  64668. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64669. _this._transformMatrix = BABYLON.Matrix.Zero();
  64670. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64671. _this._adaptiveBlurKernel = 0;
  64672. _this._blurKernelX = 0;
  64673. _this._blurKernelY = 0;
  64674. _this._blurRatio = 1.0;
  64675. _this.ignoreCameraViewport = true;
  64676. _this._updateGammaSpace();
  64677. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64678. _this._updateGammaSpace;
  64679. });
  64680. _this.onBeforeRenderObservable.add(function () {
  64681. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64682. _this._savedViewMatrix = scene.getViewMatrix();
  64683. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64684. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64685. scene.clipPlane = _this.mirrorPlane;
  64686. scene.getEngine().cullBackFaces = false;
  64687. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64688. });
  64689. _this.onAfterRenderObservable.add(function () {
  64690. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64691. scene.getEngine().cullBackFaces = true;
  64692. scene._mirroredCameraPosition = null;
  64693. delete scene.clipPlane;
  64694. });
  64695. return _this;
  64696. }
  64697. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64698. get: function () {
  64699. return this._blurRatio;
  64700. },
  64701. set: function (value) {
  64702. if (this._blurRatio === value) {
  64703. return;
  64704. }
  64705. this._blurRatio = value;
  64706. this._preparePostProcesses();
  64707. },
  64708. enumerable: true,
  64709. configurable: true
  64710. });
  64711. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64712. set: function (value) {
  64713. this._adaptiveBlurKernel = value;
  64714. this._autoComputeBlurKernel();
  64715. },
  64716. enumerable: true,
  64717. configurable: true
  64718. });
  64719. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64720. set: function (value) {
  64721. this.blurKernelX = value;
  64722. this.blurKernelY = value;
  64723. },
  64724. enumerable: true,
  64725. configurable: true
  64726. });
  64727. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64728. get: function () {
  64729. return this._blurKernelX;
  64730. },
  64731. set: function (value) {
  64732. if (this._blurKernelX === value) {
  64733. return;
  64734. }
  64735. this._blurKernelX = value;
  64736. this._preparePostProcesses();
  64737. },
  64738. enumerable: true,
  64739. configurable: true
  64740. });
  64741. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64742. get: function () {
  64743. return this._blurKernelY;
  64744. },
  64745. set: function (value) {
  64746. if (this._blurKernelY === value) {
  64747. return;
  64748. }
  64749. this._blurKernelY = value;
  64750. this._preparePostProcesses();
  64751. },
  64752. enumerable: true,
  64753. configurable: true
  64754. });
  64755. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64756. var engine = this.getScene().getEngine();
  64757. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64758. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64759. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64760. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64761. };
  64762. MirrorTexture.prototype._onRatioRescale = function () {
  64763. if (this._sizeRatio) {
  64764. this.resize(this._initialSizeParameter);
  64765. if (!this._adaptiveBlurKernel) {
  64766. this._preparePostProcesses();
  64767. }
  64768. }
  64769. if (this._adaptiveBlurKernel) {
  64770. this._autoComputeBlurKernel();
  64771. }
  64772. };
  64773. MirrorTexture.prototype._updateGammaSpace = function () {
  64774. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64775. };
  64776. MirrorTexture.prototype._preparePostProcesses = function () {
  64777. this.clearPostProcesses(true);
  64778. if (this._blurKernelX && this._blurKernelY) {
  64779. var engine = this.getScene().getEngine();
  64780. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64781. 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);
  64782. this._blurX.autoClear = false;
  64783. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64784. this._blurX.inputTexture = this._texture;
  64785. }
  64786. else {
  64787. this._blurX.alwaysForcePOT = true;
  64788. }
  64789. 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);
  64790. this._blurY.autoClear = false;
  64791. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64792. this.addPostProcess(this._blurX);
  64793. this.addPostProcess(this._blurY);
  64794. }
  64795. else {
  64796. if (this._blurY) {
  64797. this.removePostProcess(this._blurY);
  64798. this._blurY.dispose();
  64799. this._blurY = null;
  64800. }
  64801. if (this._blurX) {
  64802. this.removePostProcess(this._blurX);
  64803. this._blurX.dispose();
  64804. this._blurX = null;
  64805. }
  64806. }
  64807. };
  64808. MirrorTexture.prototype.clone = function () {
  64809. var scene = this.getScene();
  64810. if (!scene) {
  64811. return this;
  64812. }
  64813. var textureSize = this.getSize();
  64814. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64815. // Base texture
  64816. newTexture.hasAlpha = this.hasAlpha;
  64817. newTexture.level = this.level;
  64818. // Mirror Texture
  64819. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64820. if (this.renderList) {
  64821. newTexture.renderList = this.renderList.slice(0);
  64822. }
  64823. return newTexture;
  64824. };
  64825. MirrorTexture.prototype.serialize = function () {
  64826. if (!this.name) {
  64827. return null;
  64828. }
  64829. var serializationObject = _super.prototype.serialize.call(this);
  64830. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64831. return serializationObject;
  64832. };
  64833. MirrorTexture.prototype.dispose = function () {
  64834. _super.prototype.dispose.call(this);
  64835. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64836. };
  64837. return MirrorTexture;
  64838. }(BABYLON.RenderTargetTexture));
  64839. BABYLON.MirrorTexture = MirrorTexture;
  64840. })(BABYLON || (BABYLON = {}));
  64841. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64842. var BABYLON;
  64843. (function (BABYLON) {
  64844. /**
  64845. * Creates a refraction texture used by refraction channel of the standard material.
  64846. * @param name the texture name
  64847. * @param size size of the underlying texture
  64848. * @param scene root scene
  64849. */
  64850. var RefractionTexture = /** @class */ (function (_super) {
  64851. __extends(RefractionTexture, _super);
  64852. function RefractionTexture(name, size, scene, generateMipMaps) {
  64853. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64854. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64855. _this.depth = 2.0;
  64856. _this.onBeforeRenderObservable.add(function () {
  64857. scene.clipPlane = _this.refractionPlane;
  64858. });
  64859. _this.onAfterRenderObservable.add(function () {
  64860. delete scene.clipPlane;
  64861. });
  64862. return _this;
  64863. }
  64864. RefractionTexture.prototype.clone = function () {
  64865. var scene = this.getScene();
  64866. if (!scene) {
  64867. return this;
  64868. }
  64869. var textureSize = this.getSize();
  64870. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64871. // Base texture
  64872. newTexture.hasAlpha = this.hasAlpha;
  64873. newTexture.level = this.level;
  64874. // Refraction Texture
  64875. newTexture.refractionPlane = this.refractionPlane.clone();
  64876. if (this.renderList) {
  64877. newTexture.renderList = this.renderList.slice(0);
  64878. }
  64879. newTexture.depth = this.depth;
  64880. return newTexture;
  64881. };
  64882. RefractionTexture.prototype.serialize = function () {
  64883. if (!this.name) {
  64884. return null;
  64885. }
  64886. var serializationObject = _super.prototype.serialize.call(this);
  64887. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64888. serializationObject.depth = this.depth;
  64889. return serializationObject;
  64890. };
  64891. return RefractionTexture;
  64892. }(BABYLON.RenderTargetTexture));
  64893. BABYLON.RefractionTexture = RefractionTexture;
  64894. })(BABYLON || (BABYLON = {}));
  64895. //# sourceMappingURL=babylon.refractionTexture.js.map
  64896. var BABYLON;
  64897. (function (BABYLON) {
  64898. /**
  64899. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64900. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64901. */
  64902. var DynamicTexture = /** @class */ (function (_super) {
  64903. __extends(DynamicTexture, _super);
  64904. /**
  64905. * Creates a {BABYLON.DynamicTexture}
  64906. * @param name defines the name of the texture
  64907. * @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
  64908. * @param scene defines the scene where you want the texture
  64909. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64910. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64911. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64912. */
  64913. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64914. if (scene === void 0) { scene = null; }
  64915. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64916. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64917. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64918. _this.name = name;
  64919. _this._engine = _this.getScene().getEngine();
  64920. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64921. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64922. _this._generateMipMaps = generateMipMaps;
  64923. if (options.getContext) {
  64924. _this._canvas = options;
  64925. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64926. }
  64927. else {
  64928. _this._canvas = document.createElement("canvas");
  64929. if (options.width || options.width === 0) {
  64930. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64931. }
  64932. else {
  64933. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64934. }
  64935. }
  64936. var textureSize = _this.getSize();
  64937. _this._canvas.width = textureSize.width;
  64938. _this._canvas.height = textureSize.height;
  64939. _this._context = _this._canvas.getContext("2d");
  64940. return _this;
  64941. }
  64942. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64943. /**
  64944. * Gets the current state of canRescale
  64945. */
  64946. get: function () {
  64947. return true;
  64948. },
  64949. enumerable: true,
  64950. configurable: true
  64951. });
  64952. DynamicTexture.prototype._recreate = function (textureSize) {
  64953. this._canvas.width = textureSize.width;
  64954. this._canvas.height = textureSize.height;
  64955. this.releaseInternalTexture();
  64956. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64957. };
  64958. /**
  64959. * Scales the texture
  64960. * @param ratio the scale factor to apply to both width and height
  64961. */
  64962. DynamicTexture.prototype.scale = function (ratio) {
  64963. var textureSize = this.getSize();
  64964. textureSize.width *= ratio;
  64965. textureSize.height *= ratio;
  64966. this._recreate(textureSize);
  64967. };
  64968. /**
  64969. * Resizes the texture
  64970. * @param width the new width
  64971. * @param height the new height
  64972. */
  64973. DynamicTexture.prototype.scaleTo = function (width, height) {
  64974. var textureSize = this.getSize();
  64975. textureSize.width = width;
  64976. textureSize.height = height;
  64977. this._recreate(textureSize);
  64978. };
  64979. /**
  64980. * Gets the context of the canvas used by the texture
  64981. * @returns the canvas context of the dynamic texture
  64982. */
  64983. DynamicTexture.prototype.getContext = function () {
  64984. return this._context;
  64985. };
  64986. /**
  64987. * Clears the texture
  64988. */
  64989. DynamicTexture.prototype.clear = function () {
  64990. var size = this.getSize();
  64991. this._context.fillRect(0, 0, size.width, size.height);
  64992. };
  64993. /**
  64994. * Updates the texture
  64995. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64996. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64997. */
  64998. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64999. if (premulAlpha === void 0) { premulAlpha = false; }
  65000. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65001. };
  65002. /**
  65003. * Draws text onto the texture
  65004. * @param text defines the text to be drawn
  65005. * @param x defines the placement of the text from the left
  65006. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65007. * @param font defines the font to be used with font-style, font-size, font-name
  65008. * @param color defines the color used for the text
  65009. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65010. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65011. * @param update defines whether texture is immediately update (default is true)
  65012. */
  65013. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65014. if (update === void 0) { update = true; }
  65015. var size = this.getSize();
  65016. if (clearColor) {
  65017. this._context.fillStyle = clearColor;
  65018. this._context.fillRect(0, 0, size.width, size.height);
  65019. }
  65020. this._context.font = font;
  65021. if (x === null || x === undefined) {
  65022. var textSize = this._context.measureText(text);
  65023. x = (size.width - textSize.width) / 2;
  65024. }
  65025. if (y === null || y === undefined) {
  65026. var fontSize = parseInt((font.replace(/\D/g, '')));
  65027. y = (size.height / 2) + (fontSize / 3.65);
  65028. }
  65029. this._context.fillStyle = color;
  65030. this._context.fillText(text, x, y);
  65031. if (update) {
  65032. this.update(invertY);
  65033. }
  65034. };
  65035. /**
  65036. * Clones the texture
  65037. * @returns the clone of the texture.
  65038. */
  65039. DynamicTexture.prototype.clone = function () {
  65040. var scene = this.getScene();
  65041. if (!scene) {
  65042. return this;
  65043. }
  65044. var textureSize = this.getSize();
  65045. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65046. // Base texture
  65047. newTexture.hasAlpha = this.hasAlpha;
  65048. newTexture.level = this.level;
  65049. // Dynamic Texture
  65050. newTexture.wrapU = this.wrapU;
  65051. newTexture.wrapV = this.wrapV;
  65052. return newTexture;
  65053. };
  65054. /** @hidden */
  65055. DynamicTexture.prototype._rebuild = function () {
  65056. this.update();
  65057. };
  65058. return DynamicTexture;
  65059. }(BABYLON.Texture));
  65060. BABYLON.DynamicTexture = DynamicTexture;
  65061. })(BABYLON || (BABYLON = {}));
  65062. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65063. var BABYLON;
  65064. (function (BABYLON) {
  65065. var VideoTexture = /** @class */ (function (_super) {
  65066. __extends(VideoTexture, _super);
  65067. /**
  65068. * Creates a video texture.
  65069. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65070. * @param {string | null} name optional name, will detect from video source, if not defined
  65071. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65072. * @param {BABYLON.Scene} scene is obviously the current scene.
  65073. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65074. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65075. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65076. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65077. */
  65078. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65079. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65080. if (invertY === void 0) { invertY = false; }
  65081. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65082. if (settings === void 0) { settings = {
  65083. autoPlay: true,
  65084. loop: true,
  65085. autoUpdateTexture: true,
  65086. }; }
  65087. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65088. _this._stillImageCaptured = false;
  65089. _this._createInternalTexture = function () {
  65090. if (_this._texture != null) {
  65091. return;
  65092. }
  65093. if (!_this._engine.needPOTTextures ||
  65094. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65095. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65096. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65097. }
  65098. else {
  65099. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65100. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65101. _this._generateMipMaps = false;
  65102. }
  65103. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65104. if (!_this.video.autoplay) {
  65105. var oldHandler_1 = _this.video.onplaying;
  65106. _this.video.onplaying = function () {
  65107. _this.video.onplaying = oldHandler_1;
  65108. _this._texture.isReady = true;
  65109. _this._updateInternalTexture();
  65110. _this.video.pause();
  65111. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65112. _this.onLoadObservable.notifyObservers(_this);
  65113. }
  65114. };
  65115. _this.video.play();
  65116. }
  65117. else {
  65118. _this._texture.isReady = true;
  65119. _this._updateInternalTexture();
  65120. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65121. _this.onLoadObservable.notifyObservers(_this);
  65122. }
  65123. }
  65124. };
  65125. _this.reset = function () {
  65126. if (_this._texture == null) {
  65127. return;
  65128. }
  65129. _this._texture.dispose();
  65130. _this._texture = null;
  65131. };
  65132. _this._updateInternalTexture = function (e) {
  65133. if (_this._texture == null || !_this._texture.isReady) {
  65134. return;
  65135. }
  65136. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65137. return;
  65138. }
  65139. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65140. };
  65141. _this._engine = _this.getScene().getEngine();
  65142. _this._generateMipMaps = generateMipMaps;
  65143. _this._samplingMode = samplingMode;
  65144. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65145. _this.name = name || _this._getName(src);
  65146. _this.video = _this._getVideo(src);
  65147. if (settings.autoPlay !== undefined) {
  65148. _this.video.autoplay = settings.autoPlay;
  65149. }
  65150. if (settings.loop !== undefined) {
  65151. _this.video.loop = settings.loop;
  65152. }
  65153. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65154. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65155. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65156. _this.video.addEventListener("emptied", _this.reset);
  65157. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65158. _this._createInternalTexture();
  65159. }
  65160. return _this;
  65161. }
  65162. VideoTexture.prototype._getName = function (src) {
  65163. if (src instanceof HTMLVideoElement) {
  65164. return src.currentSrc;
  65165. }
  65166. if (typeof src === "object") {
  65167. return src.toString();
  65168. }
  65169. return src;
  65170. };
  65171. ;
  65172. VideoTexture.prototype._getVideo = function (src) {
  65173. if (src instanceof HTMLVideoElement) {
  65174. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65175. return src;
  65176. }
  65177. var video = document.createElement("video");
  65178. if (typeof src === "string") {
  65179. BABYLON.Tools.SetCorsBehavior(src, video);
  65180. video.src = src;
  65181. }
  65182. else {
  65183. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65184. src.forEach(function (url) {
  65185. var source = document.createElement("source");
  65186. source.src = url;
  65187. video.appendChild(source);
  65188. });
  65189. }
  65190. return video;
  65191. };
  65192. ;
  65193. /**
  65194. * Internal method to initiate `update`.
  65195. */
  65196. VideoTexture.prototype._rebuild = function () {
  65197. this.update();
  65198. };
  65199. /**
  65200. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65201. */
  65202. VideoTexture.prototype.update = function () {
  65203. if (!this.autoUpdateTexture) {
  65204. // Expecting user to call `updateTexture` manually
  65205. return;
  65206. }
  65207. this.updateTexture(true);
  65208. };
  65209. /**
  65210. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65211. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65212. */
  65213. VideoTexture.prototype.updateTexture = function (isVisible) {
  65214. if (!isVisible) {
  65215. return;
  65216. }
  65217. if (this.video.paused && this._stillImageCaptured) {
  65218. return;
  65219. }
  65220. this._stillImageCaptured = true;
  65221. this._updateInternalTexture();
  65222. };
  65223. /**
  65224. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65225. * @param url New url.
  65226. */
  65227. VideoTexture.prototype.updateURL = function (url) {
  65228. this.video.src = url;
  65229. };
  65230. VideoTexture.prototype.dispose = function () {
  65231. _super.prototype.dispose.call(this);
  65232. this.video.removeEventListener("canplay", this._createInternalTexture);
  65233. this.video.removeEventListener("paused", this._updateInternalTexture);
  65234. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65235. this.video.removeEventListener("emptied", this.reset);
  65236. this.video.pause();
  65237. };
  65238. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65239. var video = document.createElement("video");
  65240. var constraintsDeviceId;
  65241. if (constraints && constraints.deviceId) {
  65242. constraintsDeviceId = {
  65243. exact: constraints.deviceId,
  65244. };
  65245. }
  65246. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65247. if (navigator.mediaDevices) {
  65248. navigator.mediaDevices.getUserMedia({ video: constraints })
  65249. .then(function (stream) {
  65250. if (video.mozSrcObject !== undefined) {
  65251. // hack for Firefox < 19
  65252. video.mozSrcObject = stream;
  65253. }
  65254. else {
  65255. video.srcObject = stream;
  65256. }
  65257. var onPlaying = function () {
  65258. if (onReady) {
  65259. onReady(new VideoTexture("video", video, scene, true, true));
  65260. }
  65261. video.removeEventListener("playing", onPlaying);
  65262. };
  65263. video.addEventListener("playing", onPlaying);
  65264. video.play();
  65265. })
  65266. .catch(function (err) {
  65267. BABYLON.Tools.Error(err.name);
  65268. });
  65269. }
  65270. else {
  65271. navigator.getUserMedia =
  65272. navigator.getUserMedia ||
  65273. navigator.webkitGetUserMedia ||
  65274. navigator.mozGetUserMedia ||
  65275. navigator.msGetUserMedia;
  65276. if (navigator.getUserMedia) {
  65277. navigator.getUserMedia({
  65278. video: {
  65279. deviceId: constraintsDeviceId,
  65280. width: {
  65281. min: (constraints && constraints.minWidth) || 256,
  65282. max: (constraints && constraints.maxWidth) || 640,
  65283. },
  65284. height: {
  65285. min: (constraints && constraints.minHeight) || 256,
  65286. max: (constraints && constraints.maxHeight) || 480,
  65287. },
  65288. },
  65289. }, function (stream) {
  65290. if (video.mozSrcObject !== undefined) {
  65291. // hack for Firefox < 19
  65292. video.mozSrcObject = stream;
  65293. }
  65294. else {
  65295. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65296. }
  65297. video.play();
  65298. if (onReady) {
  65299. onReady(new VideoTexture("video", video, scene, true, true));
  65300. }
  65301. }, function (e) {
  65302. BABYLON.Tools.Error(e.name);
  65303. });
  65304. }
  65305. }
  65306. };
  65307. return VideoTexture;
  65308. }(BABYLON.Texture));
  65309. BABYLON.VideoTexture = VideoTexture;
  65310. })(BABYLON || (BABYLON = {}));
  65311. //# sourceMappingURL=babylon.videoTexture.js.map
  65312. var BABYLON;
  65313. (function (BABYLON) {
  65314. var RawTexture = /** @class */ (function (_super) {
  65315. __extends(RawTexture, _super);
  65316. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65317. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65318. if (invertY === void 0) { invertY = false; }
  65319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65320. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65321. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65322. _this.format = format;
  65323. _this._engine = scene.getEngine();
  65324. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65325. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65326. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65327. return _this;
  65328. }
  65329. RawTexture.prototype.update = function (data) {
  65330. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65331. };
  65332. // Statics
  65333. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65334. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65335. if (invertY === void 0) { invertY = false; }
  65336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65337. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65338. };
  65339. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65340. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65341. if (invertY === void 0) { invertY = false; }
  65342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65343. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65344. };
  65345. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65346. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65347. if (invertY === void 0) { invertY = false; }
  65348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65349. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65350. };
  65351. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65352. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65353. if (invertY === void 0) { invertY = false; }
  65354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65355. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65356. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65357. };
  65358. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65359. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65360. if (invertY === void 0) { invertY = false; }
  65361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65362. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65363. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65364. };
  65365. return RawTexture;
  65366. }(BABYLON.Texture));
  65367. BABYLON.RawTexture = RawTexture;
  65368. })(BABYLON || (BABYLON = {}));
  65369. //# sourceMappingURL=babylon.rawTexture.js.map
  65370. var BABYLON;
  65371. (function (BABYLON) {
  65372. /**
  65373. * Class used to store 3D textures containing user data
  65374. */
  65375. var RawTexture3D = /** @class */ (function (_super) {
  65376. __extends(RawTexture3D, _super);
  65377. /**
  65378. * Create a new RawTexture3D
  65379. * @param data defines the data of the texture
  65380. * @param width defines the width of the texture
  65381. * @param height defines the height of the texture
  65382. * @param depth defines the depth of the texture
  65383. * @param format defines the texture format to use
  65384. * @param scene defines the hosting scene
  65385. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65386. * @param invertY defines if texture must be stored with Y axis inverted
  65387. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65388. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65389. */
  65390. function RawTexture3D(data, width, height, depth,
  65391. /** Gets or sets the texture format to use */
  65392. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65393. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65394. if (invertY === void 0) { invertY = false; }
  65395. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65396. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65397. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65398. _this.format = format;
  65399. _this._engine = scene.getEngine();
  65400. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65401. _this.is3D = true;
  65402. return _this;
  65403. }
  65404. /**
  65405. * Update the texture with new data
  65406. * @param data defines the data to store in the texture
  65407. */
  65408. RawTexture3D.prototype.update = function (data) {
  65409. if (!this._texture) {
  65410. return;
  65411. }
  65412. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65413. };
  65414. return RawTexture3D;
  65415. }(BABYLON.Texture));
  65416. BABYLON.RawTexture3D = RawTexture3D;
  65417. })(BABYLON || (BABYLON = {}));
  65418. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65419. var BABYLON;
  65420. (function (BABYLON) {
  65421. /**
  65422. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65423. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65424. */
  65425. var PostProcess = /** @class */ (function () {
  65426. /**
  65427. * Creates a new instance PostProcess
  65428. * @param name The name of the PostProcess.
  65429. * @param fragmentUrl The url of the fragment shader to be used.
  65430. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65431. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65432. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65433. * @param camera The camera to apply the render pass to.
  65434. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65435. * @param engine The engine which the post process will be applied. (default: current engine)
  65436. * @param reusable If the post process can be reused on the same frame. (default: false)
  65437. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65438. * @param textureType Type of textures used when performing the post process. (default: 0)
  65439. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65440. * @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
  65441. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65442. */
  65443. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65444. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65445. if (defines === void 0) { defines = null; }
  65446. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65447. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65448. if (blockCompilation === void 0) { blockCompilation = false; }
  65449. this.name = name;
  65450. /**
  65451. * Width of the texture to apply the post process on
  65452. */
  65453. this.width = -1;
  65454. /**
  65455. * Height of the texture to apply the post process on
  65456. */
  65457. this.height = -1;
  65458. /**
  65459. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65460. */
  65461. this._outputTexture = null;
  65462. /**
  65463. * If the buffer needs to be cleared before applying the post process. (default: true)
  65464. * Should be set to false if shader will overwrite all previous pixels.
  65465. */
  65466. this.autoClear = true;
  65467. /**
  65468. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65469. */
  65470. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65471. /**
  65472. * Animations to be used for the post processing
  65473. */
  65474. this.animations = new Array();
  65475. /**
  65476. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65477. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65478. */
  65479. this.enablePixelPerfectMode = false;
  65480. /**
  65481. * Force the postprocess to be applied without taking in account viewport
  65482. */
  65483. this.forceFullscreenViewport = true;
  65484. /**
  65485. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65486. *
  65487. * | Value | Type | Description |
  65488. * | ----- | ----------------------------------- | ----------- |
  65489. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65490. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65491. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65492. *
  65493. */
  65494. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65495. /**
  65496. * Force textures to be a power of two (default: false)
  65497. */
  65498. this.alwaysForcePOT = false;
  65499. /**
  65500. * Number of sample textures (default: 1)
  65501. */
  65502. this.samples = 1;
  65503. /**
  65504. * Modify the scale of the post process to be the same as the viewport (default: false)
  65505. */
  65506. this.adaptScaleToCurrentViewport = false;
  65507. this._reusable = false;
  65508. /**
  65509. * Smart array of input and output textures for the post process.
  65510. */
  65511. this._textures = new BABYLON.SmartArray(2);
  65512. /**
  65513. * The index in _textures that corresponds to the output texture.
  65514. */
  65515. this._currentRenderTextureInd = 0;
  65516. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65517. this._texelSize = BABYLON.Vector2.Zero();
  65518. // Events
  65519. /**
  65520. * An event triggered when the postprocess is activated.
  65521. */
  65522. this.onActivateObservable = new BABYLON.Observable();
  65523. /**
  65524. * An event triggered when the postprocess changes its size.
  65525. */
  65526. this.onSizeChangedObservable = new BABYLON.Observable();
  65527. /**
  65528. * An event triggered when the postprocess applies its effect.
  65529. */
  65530. this.onApplyObservable = new BABYLON.Observable();
  65531. /**
  65532. * An event triggered before rendering the postprocess
  65533. */
  65534. this.onBeforeRenderObservable = new BABYLON.Observable();
  65535. /**
  65536. * An event triggered after rendering the postprocess
  65537. */
  65538. this.onAfterRenderObservable = new BABYLON.Observable();
  65539. if (camera != null) {
  65540. this._camera = camera;
  65541. this._scene = camera.getScene();
  65542. camera.attachPostProcess(this);
  65543. this._engine = this._scene.getEngine();
  65544. this._scene.postProcesses.push(this);
  65545. }
  65546. else if (engine) {
  65547. this._engine = engine;
  65548. this._engine.postProcesses.push(this);
  65549. }
  65550. this._options = options;
  65551. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65552. this._reusable = reusable || false;
  65553. this._textureType = textureType;
  65554. this._samplers = samplers || [];
  65555. this._samplers.push("textureSampler");
  65556. this._fragmentUrl = fragmentUrl;
  65557. this._vertexUrl = vertexUrl;
  65558. this._parameters = parameters || [];
  65559. this._parameters.push("scale");
  65560. this._indexParameters = indexParameters;
  65561. if (!blockCompilation) {
  65562. this.updateEffect(defines);
  65563. }
  65564. }
  65565. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65566. /**
  65567. * A function that is added to the onActivateObservable
  65568. */
  65569. set: function (callback) {
  65570. if (this._onActivateObserver) {
  65571. this.onActivateObservable.remove(this._onActivateObserver);
  65572. }
  65573. if (callback) {
  65574. this._onActivateObserver = this.onActivateObservable.add(callback);
  65575. }
  65576. },
  65577. enumerable: true,
  65578. configurable: true
  65579. });
  65580. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65581. /**
  65582. * A function that is added to the onSizeChangedObservable
  65583. */
  65584. set: function (callback) {
  65585. if (this._onSizeChangedObserver) {
  65586. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65587. }
  65588. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65589. },
  65590. enumerable: true,
  65591. configurable: true
  65592. });
  65593. Object.defineProperty(PostProcess.prototype, "onApply", {
  65594. /**
  65595. * A function that is added to the onApplyObservable
  65596. */
  65597. set: function (callback) {
  65598. if (this._onApplyObserver) {
  65599. this.onApplyObservable.remove(this._onApplyObserver);
  65600. }
  65601. this._onApplyObserver = this.onApplyObservable.add(callback);
  65602. },
  65603. enumerable: true,
  65604. configurable: true
  65605. });
  65606. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65607. /**
  65608. * A function that is added to the onBeforeRenderObservable
  65609. */
  65610. set: function (callback) {
  65611. if (this._onBeforeRenderObserver) {
  65612. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65613. }
  65614. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65615. },
  65616. enumerable: true,
  65617. configurable: true
  65618. });
  65619. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65620. /**
  65621. * A function that is added to the onAfterRenderObservable
  65622. */
  65623. set: function (callback) {
  65624. if (this._onAfterRenderObserver) {
  65625. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65626. }
  65627. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65628. },
  65629. enumerable: true,
  65630. configurable: true
  65631. });
  65632. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65633. /**
  65634. * 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
  65635. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65636. */
  65637. get: function () {
  65638. return this._textures.data[this._currentRenderTextureInd];
  65639. },
  65640. set: function (value) {
  65641. this._forcedOutputTexture = value;
  65642. },
  65643. enumerable: true,
  65644. configurable: true
  65645. });
  65646. /**
  65647. * Gets the camera which post process is applied to.
  65648. * @returns The camera the post process is applied to.
  65649. */
  65650. PostProcess.prototype.getCamera = function () {
  65651. return this._camera;
  65652. };
  65653. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65654. /**
  65655. * Gets the texel size of the postprocess.
  65656. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65657. */
  65658. get: function () {
  65659. if (this._shareOutputWithPostProcess) {
  65660. return this._shareOutputWithPostProcess.texelSize;
  65661. }
  65662. if (this._forcedOutputTexture) {
  65663. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65664. }
  65665. return this._texelSize;
  65666. },
  65667. enumerable: true,
  65668. configurable: true
  65669. });
  65670. /**
  65671. * Gets the engine which this post process belongs to.
  65672. * @returns The engine the post process was enabled with.
  65673. */
  65674. PostProcess.prototype.getEngine = function () {
  65675. return this._engine;
  65676. };
  65677. /**
  65678. * The effect that is created when initializing the post process.
  65679. * @returns The created effect corrisponding the the postprocess.
  65680. */
  65681. PostProcess.prototype.getEffect = function () {
  65682. return this._effect;
  65683. };
  65684. /**
  65685. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65686. * @param postProcess The post process to share the output with.
  65687. * @returns This post process.
  65688. */
  65689. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65690. this._disposeTextures();
  65691. this._shareOutputWithPostProcess = postProcess;
  65692. return this;
  65693. };
  65694. /**
  65695. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65696. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65697. */
  65698. PostProcess.prototype.useOwnOutput = function () {
  65699. if (this._textures.length == 0) {
  65700. this._textures = new BABYLON.SmartArray(2);
  65701. }
  65702. this._shareOutputWithPostProcess = null;
  65703. };
  65704. /**
  65705. * Updates the effect with the current post process compile time values and recompiles the shader.
  65706. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65707. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65708. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65709. * @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
  65710. * @param onCompiled Called when the shader has been compiled.
  65711. * @param onError Called if there is an error when compiling a shader.
  65712. */
  65713. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65714. if (defines === void 0) { defines = null; }
  65715. if (uniforms === void 0) { uniforms = null; }
  65716. if (samplers === void 0) { samplers = null; }
  65717. 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);
  65718. };
  65719. /**
  65720. * The post process is reusable if it can be used multiple times within one frame.
  65721. * @returns If the post process is reusable
  65722. */
  65723. PostProcess.prototype.isReusable = function () {
  65724. return this._reusable;
  65725. };
  65726. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65727. PostProcess.prototype.markTextureDirty = function () {
  65728. this.width = -1;
  65729. };
  65730. /**
  65731. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65732. * 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.
  65733. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65734. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65735. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65736. * @returns The target texture that was bound to be written to.
  65737. */
  65738. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65739. var _this = this;
  65740. if (sourceTexture === void 0) { sourceTexture = null; }
  65741. camera = camera || this._camera;
  65742. var scene = camera.getScene();
  65743. var engine = scene.getEngine();
  65744. var maxSize = engine.getCaps().maxTextureSize;
  65745. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65746. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65747. // 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
  65748. var webVRCamera = camera.parent;
  65749. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65750. requiredWidth /= 2;
  65751. }
  65752. var desiredWidth = (this._options.width || requiredWidth);
  65753. var desiredHeight = this._options.height || requiredHeight;
  65754. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65755. if (this.adaptScaleToCurrentViewport) {
  65756. var currentViewport = engine.currentViewport;
  65757. if (currentViewport) {
  65758. desiredWidth *= currentViewport.width;
  65759. desiredHeight *= currentViewport.height;
  65760. }
  65761. }
  65762. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65763. if (!this._options.width) {
  65764. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65765. }
  65766. if (!this._options.height) {
  65767. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65768. }
  65769. }
  65770. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65771. if (this._textures.length > 0) {
  65772. for (var i = 0; i < this._textures.length; i++) {
  65773. this._engine._releaseTexture(this._textures.data[i]);
  65774. }
  65775. this._textures.reset();
  65776. }
  65777. this.width = desiredWidth;
  65778. this.height = desiredHeight;
  65779. var textureSize = { width: this.width, height: this.height };
  65780. var textureOptions = {
  65781. generateMipMaps: false,
  65782. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65783. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65784. samplingMode: this.renderTargetSamplingMode,
  65785. type: this._textureType
  65786. };
  65787. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65788. if (this._reusable) {
  65789. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65790. }
  65791. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65792. this.onSizeChangedObservable.notifyObservers(this);
  65793. }
  65794. this._textures.forEach(function (texture) {
  65795. if (texture.samples !== _this.samples) {
  65796. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65797. }
  65798. });
  65799. }
  65800. var target;
  65801. if (this._shareOutputWithPostProcess) {
  65802. target = this._shareOutputWithPostProcess.inputTexture;
  65803. }
  65804. else if (this._forcedOutputTexture) {
  65805. target = this._forcedOutputTexture;
  65806. this.width = this._forcedOutputTexture.width;
  65807. this.height = this._forcedOutputTexture.height;
  65808. }
  65809. else {
  65810. target = this.inputTexture;
  65811. }
  65812. // Bind the input of this post process to be used as the output of the previous post process.
  65813. if (this.enablePixelPerfectMode) {
  65814. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65815. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65816. }
  65817. else {
  65818. this._scaleRatio.copyFromFloats(1, 1);
  65819. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65820. }
  65821. this.onActivateObservable.notifyObservers(camera);
  65822. // Clear
  65823. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65824. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65825. }
  65826. if (this._reusable) {
  65827. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65828. }
  65829. return target;
  65830. };
  65831. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65832. /**
  65833. * If the post process is supported.
  65834. */
  65835. get: function () {
  65836. return this._effect.isSupported;
  65837. },
  65838. enumerable: true,
  65839. configurable: true
  65840. });
  65841. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65842. /**
  65843. * The aspect ratio of the output texture.
  65844. */
  65845. get: function () {
  65846. if (this._shareOutputWithPostProcess) {
  65847. return this._shareOutputWithPostProcess.aspectRatio;
  65848. }
  65849. if (this._forcedOutputTexture) {
  65850. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65851. }
  65852. return this.width / this.height;
  65853. },
  65854. enumerable: true,
  65855. configurable: true
  65856. });
  65857. /**
  65858. * Get a value indicating if the post-process is ready to be used
  65859. * @returns true if the post-process is ready (shader is compiled)
  65860. */
  65861. PostProcess.prototype.isReady = function () {
  65862. return this._effect && this._effect.isReady();
  65863. };
  65864. /**
  65865. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65866. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65867. */
  65868. PostProcess.prototype.apply = function () {
  65869. // Check
  65870. if (!this._effect || !this._effect.isReady())
  65871. return null;
  65872. // States
  65873. this._engine.enableEffect(this._effect);
  65874. this._engine.setState(false);
  65875. this._engine.setDepthBuffer(false);
  65876. this._engine.setDepthWrite(false);
  65877. // Alpha
  65878. this._engine.setAlphaMode(this.alphaMode);
  65879. if (this.alphaConstants) {
  65880. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65881. }
  65882. // Bind the output texture of the preivous post process as the input to this post process.
  65883. var source;
  65884. if (this._shareOutputWithPostProcess) {
  65885. source = this._shareOutputWithPostProcess.inputTexture;
  65886. }
  65887. else if (this._forcedOutputTexture) {
  65888. source = this._forcedOutputTexture;
  65889. }
  65890. else {
  65891. source = this.inputTexture;
  65892. }
  65893. this._effect._bindTexture("textureSampler", source);
  65894. // Parameters
  65895. this._effect.setVector2("scale", this._scaleRatio);
  65896. this.onApplyObservable.notifyObservers(this._effect);
  65897. return this._effect;
  65898. };
  65899. PostProcess.prototype._disposeTextures = function () {
  65900. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65901. return;
  65902. }
  65903. if (this._textures.length > 0) {
  65904. for (var i = 0; i < this._textures.length; i++) {
  65905. this._engine._releaseTexture(this._textures.data[i]);
  65906. }
  65907. }
  65908. this._textures.dispose();
  65909. };
  65910. /**
  65911. * Disposes the post process.
  65912. * @param camera The camera to dispose the post process on.
  65913. */
  65914. PostProcess.prototype.dispose = function (camera) {
  65915. camera = camera || this._camera;
  65916. this._disposeTextures();
  65917. if (this._scene) {
  65918. var index_1 = this._scene.postProcesses.indexOf(this);
  65919. if (index_1 !== -1) {
  65920. this._scene.postProcesses.splice(index_1, 1);
  65921. }
  65922. }
  65923. else {
  65924. var index_2 = this._engine.postProcesses.indexOf(this);
  65925. if (index_2 !== -1) {
  65926. this._engine.postProcesses.splice(index_2, 1);
  65927. }
  65928. }
  65929. if (!camera) {
  65930. return;
  65931. }
  65932. camera.detachPostProcess(this);
  65933. var index = camera._postProcesses.indexOf(this);
  65934. if (index === 0 && camera._postProcesses.length > 0) {
  65935. var firstPostProcess = this._camera._getFirstPostProcess();
  65936. if (firstPostProcess) {
  65937. firstPostProcess.markTextureDirty();
  65938. }
  65939. }
  65940. this.onActivateObservable.clear();
  65941. this.onAfterRenderObservable.clear();
  65942. this.onApplyObservable.clear();
  65943. this.onBeforeRenderObservable.clear();
  65944. this.onSizeChangedObservable.clear();
  65945. };
  65946. return PostProcess;
  65947. }());
  65948. BABYLON.PostProcess = PostProcess;
  65949. })(BABYLON || (BABYLON = {}));
  65950. //# sourceMappingURL=babylon.postProcess.js.map
  65951. var BABYLON;
  65952. (function (BABYLON) {
  65953. var PassPostProcess = /** @class */ (function (_super) {
  65954. __extends(PassPostProcess, _super);
  65955. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65956. if (camera === void 0) { camera = null; }
  65957. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65958. if (blockCompilation === void 0) { blockCompilation = false; }
  65959. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65960. }
  65961. return PassPostProcess;
  65962. }(BABYLON.PostProcess));
  65963. BABYLON.PassPostProcess = PassPostProcess;
  65964. })(BABYLON || (BABYLON = {}));
  65965. //# sourceMappingURL=babylon.passPostProcess.js.map
  65966. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65967. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65968. s = arguments[i];
  65969. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65970. t[p] = s[p];
  65971. }
  65972. return t;
  65973. };
  65974. var BABYLON;
  65975. (function (BABYLON) {
  65976. /**
  65977. * Default implementation IShadowGenerator.
  65978. * This is the main object responsible of generating shadows in the framework.
  65979. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65980. */
  65981. var ShadowGenerator = /** @class */ (function () {
  65982. /**
  65983. * Creates a ShadowGenerator object.
  65984. * A ShadowGenerator is the required tool to use the shadows.
  65985. * Each light casting shadows needs to use its own ShadowGenerator.
  65986. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65987. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65988. * @param light The light object generating the shadows.
  65989. * @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.
  65990. */
  65991. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65992. this._bias = 0.00005;
  65993. this._normalBias = 0;
  65994. this._blurBoxOffset = 1;
  65995. this._blurScale = 2;
  65996. this._blurKernel = 1;
  65997. this._useKernelBlur = false;
  65998. this._filter = ShadowGenerator.FILTER_NONE;
  65999. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66000. this._contactHardeningLightSizeUVRatio = 0.1;
  66001. this._darkness = 0;
  66002. this._transparencyShadow = false;
  66003. /**
  66004. * Controls the extent to which the shadows fade out at the edge of the frustum
  66005. * Used only by directionals and spots
  66006. */
  66007. this.frustumEdgeFalloff = 0;
  66008. /**
  66009. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66010. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66011. * It might on the other hand introduce peter panning.
  66012. */
  66013. this.forceBackFacesOnly = false;
  66014. this._lightDirection = BABYLON.Vector3.Zero();
  66015. this._viewMatrix = BABYLON.Matrix.Zero();
  66016. this._projectionMatrix = BABYLON.Matrix.Zero();
  66017. this._transformMatrix = BABYLON.Matrix.Zero();
  66018. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66019. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66020. this._currentFaceIndex = 0;
  66021. this._currentFaceIndexCache = 0;
  66022. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66023. this._mapSize = mapSize;
  66024. this._light = light;
  66025. this._scene = light.getScene();
  66026. light._shadowGenerator = this;
  66027. // Texture type fallback from float to int if not supported.
  66028. var caps = this._scene.getEngine().getCaps();
  66029. if (!useFullFloatFirst) {
  66030. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66031. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66032. }
  66033. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66034. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66035. }
  66036. else {
  66037. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66038. }
  66039. }
  66040. else {
  66041. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66042. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66043. }
  66044. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66045. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66046. }
  66047. else {
  66048. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66049. }
  66050. }
  66051. this._initializeGenerator();
  66052. this._applyFilterValues();
  66053. }
  66054. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66055. /**
  66056. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66057. */
  66058. get: function () {
  66059. return this._bias;
  66060. },
  66061. /**
  66062. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66063. */
  66064. set: function (bias) {
  66065. this._bias = bias;
  66066. },
  66067. enumerable: true,
  66068. configurable: true
  66069. });
  66070. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66071. /**
  66072. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66073. */
  66074. get: function () {
  66075. return this._normalBias;
  66076. },
  66077. /**
  66078. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66079. */
  66080. set: function (normalBias) {
  66081. this._normalBias = normalBias;
  66082. },
  66083. enumerable: true,
  66084. configurable: true
  66085. });
  66086. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66087. /**
  66088. * Gets the blur box offset: offset applied during the blur pass.
  66089. * Only usefull if useKernelBlur = false
  66090. */
  66091. get: function () {
  66092. return this._blurBoxOffset;
  66093. },
  66094. /**
  66095. * Sets the blur box offset: offset applied during the blur pass.
  66096. * Only usefull if useKernelBlur = false
  66097. */
  66098. set: function (value) {
  66099. if (this._blurBoxOffset === value) {
  66100. return;
  66101. }
  66102. this._blurBoxOffset = value;
  66103. this._disposeBlurPostProcesses();
  66104. },
  66105. enumerable: true,
  66106. configurable: true
  66107. });
  66108. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66109. /**
  66110. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66111. * 2 means half of the size.
  66112. */
  66113. get: function () {
  66114. return this._blurScale;
  66115. },
  66116. /**
  66117. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66118. * 2 means half of the size.
  66119. */
  66120. set: function (value) {
  66121. if (this._blurScale === value) {
  66122. return;
  66123. }
  66124. this._blurScale = value;
  66125. this._disposeBlurPostProcesses();
  66126. },
  66127. enumerable: true,
  66128. configurable: true
  66129. });
  66130. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66131. /**
  66132. * Gets the blur kernel: kernel size of the blur pass.
  66133. * Only usefull if useKernelBlur = true
  66134. */
  66135. get: function () {
  66136. return this._blurKernel;
  66137. },
  66138. /**
  66139. * Sets the blur kernel: kernel size of the blur pass.
  66140. * Only usefull if useKernelBlur = true
  66141. */
  66142. set: function (value) {
  66143. if (this._blurKernel === value) {
  66144. return;
  66145. }
  66146. this._blurKernel = value;
  66147. this._disposeBlurPostProcesses();
  66148. },
  66149. enumerable: true,
  66150. configurable: true
  66151. });
  66152. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66153. /**
  66154. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66155. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66156. */
  66157. get: function () {
  66158. return this._useKernelBlur;
  66159. },
  66160. /**
  66161. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66162. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66163. */
  66164. set: function (value) {
  66165. if (this._useKernelBlur === value) {
  66166. return;
  66167. }
  66168. this._useKernelBlur = value;
  66169. this._disposeBlurPostProcesses();
  66170. },
  66171. enumerable: true,
  66172. configurable: true
  66173. });
  66174. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66175. /**
  66176. * Gets the depth scale used in ESM mode.
  66177. */
  66178. get: function () {
  66179. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66180. },
  66181. /**
  66182. * Sets the depth scale used in ESM mode.
  66183. * This can override the scale stored on the light.
  66184. */
  66185. set: function (value) {
  66186. this._depthScale = value;
  66187. },
  66188. enumerable: true,
  66189. configurable: true
  66190. });
  66191. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66192. /**
  66193. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66194. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66195. */
  66196. get: function () {
  66197. return this._filter;
  66198. },
  66199. /**
  66200. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66201. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66202. */
  66203. set: function (value) {
  66204. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66205. if (this._light.needCube()) {
  66206. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66207. this.useExponentialShadowMap = true;
  66208. return;
  66209. }
  66210. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66211. this.useCloseExponentialShadowMap = true;
  66212. return;
  66213. }
  66214. // PCF on cubemap would also be expensive
  66215. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66216. this.usePoissonSampling = true;
  66217. return;
  66218. }
  66219. }
  66220. // Weblg1 fallback for PCF.
  66221. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66222. if (this._scene.getEngine().webGLVersion === 1) {
  66223. this.usePoissonSampling = true;
  66224. return;
  66225. }
  66226. }
  66227. if (this._filter === value) {
  66228. return;
  66229. }
  66230. this._filter = value;
  66231. this._disposeBlurPostProcesses();
  66232. this._applyFilterValues();
  66233. this._light._markMeshesAsLightDirty();
  66234. },
  66235. enumerable: true,
  66236. configurable: true
  66237. });
  66238. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66239. /**
  66240. * Gets if the current filter is set to Poisson Sampling.
  66241. */
  66242. get: function () {
  66243. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66244. },
  66245. /**
  66246. * Sets the current filter to Poisson Sampling.
  66247. */
  66248. set: function (value) {
  66249. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66250. return;
  66251. }
  66252. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66253. },
  66254. enumerable: true,
  66255. configurable: true
  66256. });
  66257. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66258. /**
  66259. * Gets if the current filter is set to VSM.
  66260. * DEPRECATED. Should use useExponentialShadowMap instead.
  66261. */
  66262. get: function () {
  66263. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66264. return this.useExponentialShadowMap;
  66265. },
  66266. /**
  66267. * Sets the current filter is to VSM.
  66268. * DEPRECATED. Should use useExponentialShadowMap instead.
  66269. */
  66270. set: function (value) {
  66271. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66272. this.useExponentialShadowMap = value;
  66273. },
  66274. enumerable: true,
  66275. configurable: true
  66276. });
  66277. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66278. /**
  66279. * Gets if the current filter is set to blurred VSM.
  66280. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66281. */
  66282. get: function () {
  66283. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66284. return this.useBlurExponentialShadowMap;
  66285. },
  66286. /**
  66287. * Sets the current filter is to blurred VSM.
  66288. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66289. */
  66290. set: function (value) {
  66291. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66292. this.useBlurExponentialShadowMap = value;
  66293. },
  66294. enumerable: true,
  66295. configurable: true
  66296. });
  66297. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66298. /**
  66299. * Gets if the current filter is set to ESM.
  66300. */
  66301. get: function () {
  66302. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66303. },
  66304. /**
  66305. * Sets the current filter is to ESM.
  66306. */
  66307. set: function (value) {
  66308. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66309. return;
  66310. }
  66311. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66312. },
  66313. enumerable: true,
  66314. configurable: true
  66315. });
  66316. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66317. /**
  66318. * Gets if the current filter is set to filtered ESM.
  66319. */
  66320. get: function () {
  66321. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66322. },
  66323. /**
  66324. * Gets if the current filter is set to filtered ESM.
  66325. */
  66326. set: function (value) {
  66327. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66328. return;
  66329. }
  66330. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66331. },
  66332. enumerable: true,
  66333. configurable: true
  66334. });
  66335. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66336. /**
  66337. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66338. * exponential to prevent steep falloff artifacts).
  66339. */
  66340. get: function () {
  66341. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66342. },
  66343. /**
  66344. * Sets the current filter to "close ESM" (using the inverse of the
  66345. * exponential to prevent steep falloff artifacts).
  66346. */
  66347. set: function (value) {
  66348. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66349. return;
  66350. }
  66351. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66352. },
  66353. enumerable: true,
  66354. configurable: true
  66355. });
  66356. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66357. /**
  66358. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66359. * exponential to prevent steep falloff artifacts).
  66360. */
  66361. get: function () {
  66362. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66363. },
  66364. /**
  66365. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66366. * exponential to prevent steep falloff artifacts).
  66367. */
  66368. set: function (value) {
  66369. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66370. return;
  66371. }
  66372. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66373. },
  66374. enumerable: true,
  66375. configurable: true
  66376. });
  66377. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66378. /**
  66379. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66380. */
  66381. get: function () {
  66382. return this.filter === ShadowGenerator.FILTER_PCF;
  66383. },
  66384. /**
  66385. * Sets the current filter to "PCF" (percentage closer filtering).
  66386. */
  66387. set: function (value) {
  66388. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66389. return;
  66390. }
  66391. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66392. },
  66393. enumerable: true,
  66394. configurable: true
  66395. });
  66396. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66397. /**
  66398. * Gets the PCF or PCSS Quality.
  66399. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66400. */
  66401. get: function () {
  66402. return this._filteringQuality;
  66403. },
  66404. /**
  66405. * Sets the PCF or PCSS Quality.
  66406. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66407. */
  66408. set: function (filteringQuality) {
  66409. this._filteringQuality = filteringQuality;
  66410. },
  66411. enumerable: true,
  66412. configurable: true
  66413. });
  66414. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66415. /**
  66416. * Gets if the current filter is set to "PCSS" (contact hardening).
  66417. */
  66418. get: function () {
  66419. return this.filter === ShadowGenerator.FILTER_PCSS;
  66420. },
  66421. /**
  66422. * Sets the current filter to "PCSS" (contact hardening).
  66423. */
  66424. set: function (value) {
  66425. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66426. return;
  66427. }
  66428. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66429. },
  66430. enumerable: true,
  66431. configurable: true
  66432. });
  66433. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66434. /**
  66435. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66436. * Using a ratio helps keeping shape stability independently of the map size.
  66437. *
  66438. * It does not account for the light projection as it was having too much
  66439. * instability during the light setup or during light position changes.
  66440. *
  66441. * Only valid if useContactHardeningShadow is true.
  66442. */
  66443. get: function () {
  66444. return this._contactHardeningLightSizeUVRatio;
  66445. },
  66446. /**
  66447. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66448. * Using a ratio helps keeping shape stability independently of the map size.
  66449. *
  66450. * It does not account for the light projection as it was having too much
  66451. * instability during the light setup or during light position changes.
  66452. *
  66453. * Only valid if useContactHardeningShadow is true.
  66454. */
  66455. set: function (contactHardeningLightSizeUVRatio) {
  66456. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66457. },
  66458. enumerable: true,
  66459. configurable: true
  66460. });
  66461. /**
  66462. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66463. * 0 means strongest and 1 would means no shadow.
  66464. * @returns the darkness.
  66465. */
  66466. ShadowGenerator.prototype.getDarkness = function () {
  66467. return this._darkness;
  66468. };
  66469. /**
  66470. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66471. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66472. * @returns the shadow generator allowing fluent coding.
  66473. */
  66474. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66475. if (darkness >= 1.0)
  66476. this._darkness = 1.0;
  66477. else if (darkness <= 0.0)
  66478. this._darkness = 0.0;
  66479. else
  66480. this._darkness = darkness;
  66481. return this;
  66482. };
  66483. /**
  66484. * Sets the ability to have transparent shadow (boolean).
  66485. * @param transparent True if transparent else False
  66486. * @returns the shadow generator allowing fluent coding
  66487. */
  66488. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66489. this._transparencyShadow = transparent;
  66490. return this;
  66491. };
  66492. /**
  66493. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66494. * @returns The render target texture if present otherwise, null
  66495. */
  66496. ShadowGenerator.prototype.getShadowMap = function () {
  66497. return this._shadowMap;
  66498. };
  66499. /**
  66500. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66501. * @returns The render target texture if the shadow map is present otherwise, null
  66502. */
  66503. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66504. if (this._shadowMap2) {
  66505. return this._shadowMap2;
  66506. }
  66507. return this._shadowMap;
  66508. };
  66509. /**
  66510. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66511. * @param mesh Mesh to add
  66512. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66513. * @returns the Shadow Generator itself
  66514. */
  66515. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66516. if (includeDescendants === void 0) { includeDescendants = true; }
  66517. if (!this._shadowMap) {
  66518. return this;
  66519. }
  66520. if (!this._shadowMap.renderList) {
  66521. this._shadowMap.renderList = [];
  66522. }
  66523. this._shadowMap.renderList.push(mesh);
  66524. if (includeDescendants) {
  66525. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66526. }
  66527. return this;
  66528. var _a;
  66529. };
  66530. /**
  66531. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66532. * @param mesh Mesh to remove
  66533. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66534. * @returns the Shadow Generator itself
  66535. */
  66536. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66537. if (includeDescendants === void 0) { includeDescendants = true; }
  66538. if (!this._shadowMap || !this._shadowMap.renderList) {
  66539. return this;
  66540. }
  66541. var index = this._shadowMap.renderList.indexOf(mesh);
  66542. if (index !== -1) {
  66543. this._shadowMap.renderList.splice(index, 1);
  66544. }
  66545. if (includeDescendants) {
  66546. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66547. var child = _a[_i];
  66548. this.removeShadowCaster(child);
  66549. }
  66550. }
  66551. return this;
  66552. };
  66553. /**
  66554. * Returns the associated light object.
  66555. * @returns the light generating the shadow
  66556. */
  66557. ShadowGenerator.prototype.getLight = function () {
  66558. return this._light;
  66559. };
  66560. ShadowGenerator.prototype._initializeGenerator = function () {
  66561. this._light._markMeshesAsLightDirty();
  66562. this._initializeShadowMap();
  66563. };
  66564. ShadowGenerator.prototype._initializeShadowMap = function () {
  66565. var _this = this;
  66566. // Render target
  66567. var engine = this._scene.getEngine();
  66568. if (engine.webGLVersion > 1) {
  66569. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66570. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66571. }
  66572. else {
  66573. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66574. }
  66575. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66576. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66577. this._shadowMap.anisotropicFilteringLevel = 1;
  66578. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66579. this._shadowMap.renderParticles = false;
  66580. this._shadowMap.ignoreCameraViewport = true;
  66581. // Record Face Index before render.
  66582. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66583. _this._currentFaceIndex = faceIndex;
  66584. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66585. engine.setColorWrite(false);
  66586. }
  66587. });
  66588. // Custom render function.
  66589. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66590. // Blur if required afer render.
  66591. this._shadowMap.onAfterUnbindObservable.add(function () {
  66592. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66593. engine.setColorWrite(true);
  66594. }
  66595. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66596. return;
  66597. }
  66598. var shadowMap = _this.getShadowMapForRendering();
  66599. if (shadowMap) {
  66600. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66601. }
  66602. });
  66603. // Clear according to the chosen filter.
  66604. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66605. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66606. this._shadowMap.onClearObservable.add(function (engine) {
  66607. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66608. engine.clear(clearOne, false, true, false);
  66609. }
  66610. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66611. engine.clear(clearZero, true, true, false);
  66612. }
  66613. else {
  66614. engine.clear(clearOne, true, true, false);
  66615. }
  66616. });
  66617. };
  66618. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66619. var _this = this;
  66620. var engine = this._scene.getEngine();
  66621. var targetSize = this._mapSize / this.blurScale;
  66622. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66623. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66624. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66625. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66626. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66627. }
  66628. if (this.useKernelBlur) {
  66629. 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);
  66630. this._kernelBlurXPostprocess.width = targetSize;
  66631. this._kernelBlurXPostprocess.height = targetSize;
  66632. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66633. effect.setTexture("textureSampler", _this._shadowMap);
  66634. });
  66635. 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);
  66636. this._kernelBlurXPostprocess.autoClear = false;
  66637. this._kernelBlurYPostprocess.autoClear = false;
  66638. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66639. this._kernelBlurXPostprocess.packedFloat = true;
  66640. this._kernelBlurYPostprocess.packedFloat = true;
  66641. }
  66642. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66643. }
  66644. else {
  66645. 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);
  66646. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66647. effect.setFloat2("screenSize", targetSize, targetSize);
  66648. effect.setTexture("textureSampler", _this._shadowMap);
  66649. });
  66650. this._boxBlurPostprocess.autoClear = false;
  66651. this._blurPostProcesses = [this._boxBlurPostprocess];
  66652. }
  66653. };
  66654. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66655. var index;
  66656. var engine = this._scene.getEngine();
  66657. if (depthOnlySubMeshes.length) {
  66658. engine.setColorWrite(false);
  66659. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66660. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66661. }
  66662. engine.setColorWrite(true);
  66663. }
  66664. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66665. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66666. }
  66667. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66668. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66669. }
  66670. if (this._transparencyShadow) {
  66671. for (index = 0; index < transparentSubMeshes.length; index++) {
  66672. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66673. }
  66674. }
  66675. };
  66676. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66677. var _this = this;
  66678. var mesh = subMesh.getRenderingMesh();
  66679. var scene = this._scene;
  66680. var engine = scene.getEngine();
  66681. var material = subMesh.getMaterial();
  66682. if (!material) {
  66683. return;
  66684. }
  66685. // Culling
  66686. engine.setState(material.backFaceCulling);
  66687. // Managing instances
  66688. var batch = mesh._getInstancesRenderList(subMesh._id);
  66689. if (batch.mustReturn) {
  66690. return;
  66691. }
  66692. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66693. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66694. engine.enableEffect(this._effect);
  66695. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66696. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66697. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66698. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66699. this._effect.setVector3("lightData", this._cachedDirection);
  66700. }
  66701. else {
  66702. this._effect.setVector3("lightData", this._cachedPosition);
  66703. }
  66704. if (scene.activeCamera) {
  66705. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66706. }
  66707. // Alpha test
  66708. if (material && material.needAlphaTesting()) {
  66709. var alphaTexture = material.getAlphaTestTexture();
  66710. if (alphaTexture) {
  66711. this._effect.setTexture("diffuseSampler", alphaTexture);
  66712. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66713. }
  66714. }
  66715. // Bones
  66716. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66717. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66718. }
  66719. // Morph targets
  66720. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66721. if (this.forceBackFacesOnly) {
  66722. engine.setState(true, 0, false, true);
  66723. }
  66724. // Draw
  66725. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66726. if (this.forceBackFacesOnly) {
  66727. engine.setState(true, 0, false, false);
  66728. }
  66729. }
  66730. else {
  66731. // Need to reset refresh rate of the shadowMap
  66732. if (this._shadowMap) {
  66733. this._shadowMap.resetRefreshCounter();
  66734. }
  66735. }
  66736. };
  66737. ShadowGenerator.prototype._applyFilterValues = function () {
  66738. if (!this._shadowMap) {
  66739. return;
  66740. }
  66741. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66742. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66743. }
  66744. else {
  66745. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66746. }
  66747. };
  66748. /**
  66749. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66750. * @param onCompiled Callback triggered at the and of the effects compilation
  66751. * @param options Sets of optional options forcing the compilation with different modes
  66752. */
  66753. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66754. var _this = this;
  66755. var localOptions = __assign({ useInstances: false }, options);
  66756. var shadowMap = this.getShadowMap();
  66757. if (!shadowMap) {
  66758. if (onCompiled) {
  66759. onCompiled(this);
  66760. }
  66761. return;
  66762. }
  66763. var renderList = shadowMap.renderList;
  66764. if (!renderList) {
  66765. if (onCompiled) {
  66766. onCompiled(this);
  66767. }
  66768. return;
  66769. }
  66770. var subMeshes = new Array();
  66771. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66772. var mesh = renderList_1[_i];
  66773. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66774. }
  66775. if (subMeshes.length === 0) {
  66776. if (onCompiled) {
  66777. onCompiled(this);
  66778. }
  66779. return;
  66780. }
  66781. var currentIndex = 0;
  66782. var checkReady = function () {
  66783. if (!_this._scene || !_this._scene.getEngine()) {
  66784. return;
  66785. }
  66786. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66787. currentIndex++;
  66788. if (currentIndex >= subMeshes.length) {
  66789. if (onCompiled) {
  66790. onCompiled(_this);
  66791. }
  66792. return;
  66793. }
  66794. }
  66795. setTimeout(checkReady, 16);
  66796. };
  66797. checkReady();
  66798. };
  66799. /**
  66800. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66801. * @param options Sets of optional options forcing the compilation with different modes
  66802. * @returns A promise that resolves when the compilation completes
  66803. */
  66804. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66805. var _this = this;
  66806. return new Promise(function (resolve) {
  66807. _this.forceCompilation(function () {
  66808. resolve();
  66809. }, options);
  66810. });
  66811. };
  66812. /**
  66813. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66814. * @param subMesh The submesh we want to render in the shadow map
  66815. * @param useInstances Defines wether will draw in the map using instances
  66816. * @returns true if ready otherwise, false
  66817. */
  66818. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66819. var defines = [];
  66820. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66821. defines.push("#define FLOAT");
  66822. }
  66823. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66824. defines.push("#define ESM");
  66825. }
  66826. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66827. defines.push("#define DEPTHTEXTURE");
  66828. }
  66829. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66830. var mesh = subMesh.getMesh();
  66831. var material = subMesh.getMaterial();
  66832. // Normal bias.
  66833. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66834. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66835. defines.push("#define NORMAL");
  66836. if (mesh.nonUniformScaling) {
  66837. defines.push("#define NONUNIFORMSCALING");
  66838. }
  66839. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66840. defines.push("#define DIRECTIONINLIGHTDATA");
  66841. }
  66842. }
  66843. // Alpha test
  66844. if (material && material.needAlphaTesting()) {
  66845. var alphaTexture = material.getAlphaTestTexture();
  66846. if (alphaTexture) {
  66847. defines.push("#define ALPHATEST");
  66848. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66849. attribs.push(BABYLON.VertexBuffer.UVKind);
  66850. defines.push("#define UV1");
  66851. }
  66852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66853. if (alphaTexture.coordinatesIndex === 1) {
  66854. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66855. defines.push("#define UV2");
  66856. }
  66857. }
  66858. }
  66859. }
  66860. // Bones
  66861. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66864. if (mesh.numBoneInfluencers > 4) {
  66865. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66866. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66867. }
  66868. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66869. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66870. }
  66871. else {
  66872. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66873. }
  66874. // Morph targets
  66875. var manager = mesh.morphTargetManager;
  66876. var morphInfluencers = 0;
  66877. if (manager) {
  66878. if (manager.numInfluencers > 0) {
  66879. defines.push("#define MORPHTARGETS");
  66880. morphInfluencers = manager.numInfluencers;
  66881. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66882. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66883. }
  66884. }
  66885. // Instances
  66886. if (useInstances) {
  66887. defines.push("#define INSTANCES");
  66888. attribs.push("world0");
  66889. attribs.push("world1");
  66890. attribs.push("world2");
  66891. attribs.push("world3");
  66892. }
  66893. // Get correct effect
  66894. var join = defines.join("\n");
  66895. if (this._cachedDefines !== join) {
  66896. this._cachedDefines = join;
  66897. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66898. }
  66899. if (!this._effect.isReady()) {
  66900. return false;
  66901. }
  66902. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66903. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66904. this._initializeBlurRTTAndPostProcesses();
  66905. }
  66906. }
  66907. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66908. return false;
  66909. }
  66910. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66911. return false;
  66912. }
  66913. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66914. return false;
  66915. }
  66916. return true;
  66917. };
  66918. /**
  66919. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66920. * @param defines Defines of the material we want to update
  66921. * @param lightIndex Index of the light in the enabled light list of the material
  66922. */
  66923. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66924. var scene = this._scene;
  66925. var light = this._light;
  66926. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66927. return;
  66928. }
  66929. defines["SHADOW" + lightIndex] = true;
  66930. if (this.useContactHardeningShadow) {
  66931. defines["SHADOWPCSS" + lightIndex] = true;
  66932. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66933. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66934. }
  66935. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66936. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66937. }
  66938. // else default to high.
  66939. }
  66940. if (this.usePercentageCloserFiltering) {
  66941. defines["SHADOWPCF" + lightIndex] = true;
  66942. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66943. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66944. }
  66945. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66946. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66947. }
  66948. // else default to high.
  66949. }
  66950. else if (this.usePoissonSampling) {
  66951. defines["SHADOWPOISSON" + lightIndex] = true;
  66952. }
  66953. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66954. defines["SHADOWESM" + lightIndex] = true;
  66955. }
  66956. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66957. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66958. }
  66959. if (light.needCube()) {
  66960. defines["SHADOWCUBE" + lightIndex] = true;
  66961. }
  66962. };
  66963. /**
  66964. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66965. * defined in the generator but impacting the effect).
  66966. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66967. * @param effect The effect we are binfing the information for
  66968. */
  66969. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66970. var light = this._light;
  66971. var scene = this._scene;
  66972. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66973. return;
  66974. }
  66975. var camera = scene.activeCamera;
  66976. if (!camera) {
  66977. return;
  66978. }
  66979. var shadowMap = this.getShadowMap();
  66980. if (!shadowMap) {
  66981. return;
  66982. }
  66983. if (!light.needCube()) {
  66984. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66985. }
  66986. // Only PCF uses depth stencil texture.
  66987. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66988. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66989. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66990. }
  66991. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66992. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66993. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66994. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66995. }
  66996. else {
  66997. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66998. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66999. }
  67000. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67001. };
  67002. /**
  67003. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67004. * (eq to shadow prjection matrix * light transform matrix)
  67005. * @returns The transform matrix used to create the shadow map
  67006. */
  67007. ShadowGenerator.prototype.getTransformMatrix = function () {
  67008. var scene = this._scene;
  67009. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67010. return this._transformMatrix;
  67011. }
  67012. this._currentRenderID = scene.getRenderId();
  67013. this._currentFaceIndexCache = this._currentFaceIndex;
  67014. var lightPosition = this._light.position;
  67015. if (this._light.computeTransformedInformation()) {
  67016. lightPosition = this._light.transformedPosition;
  67017. }
  67018. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67019. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67020. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67021. }
  67022. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67023. this._cachedPosition.copyFrom(lightPosition);
  67024. this._cachedDirection.copyFrom(this._lightDirection);
  67025. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67026. var shadowMap = this.getShadowMap();
  67027. if (shadowMap) {
  67028. var renderList = shadowMap.renderList;
  67029. if (renderList) {
  67030. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67031. }
  67032. }
  67033. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67034. }
  67035. return this._transformMatrix;
  67036. };
  67037. /**
  67038. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67039. * Cube and 2D textures for instance.
  67040. */
  67041. ShadowGenerator.prototype.recreateShadowMap = function () {
  67042. var shadowMap = this._shadowMap;
  67043. if (!shadowMap) {
  67044. return;
  67045. }
  67046. // Track render list.
  67047. var renderList = shadowMap.renderList;
  67048. // Clean up existing data.
  67049. this._disposeRTTandPostProcesses();
  67050. // Reinitializes.
  67051. this._initializeGenerator();
  67052. // Reaffect the filter to ensure a correct fallback if necessary.
  67053. this.filter = this.filter;
  67054. // Reaffect the filter.
  67055. this._applyFilterValues();
  67056. // Reaffect Render List.
  67057. this._shadowMap.renderList = renderList;
  67058. };
  67059. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67060. if (this._shadowMap2) {
  67061. this._shadowMap2.dispose();
  67062. this._shadowMap2 = null;
  67063. }
  67064. if (this._boxBlurPostprocess) {
  67065. this._boxBlurPostprocess.dispose();
  67066. this._boxBlurPostprocess = null;
  67067. }
  67068. if (this._kernelBlurXPostprocess) {
  67069. this._kernelBlurXPostprocess.dispose();
  67070. this._kernelBlurXPostprocess = null;
  67071. }
  67072. if (this._kernelBlurYPostprocess) {
  67073. this._kernelBlurYPostprocess.dispose();
  67074. this._kernelBlurYPostprocess = null;
  67075. }
  67076. this._blurPostProcesses = [];
  67077. };
  67078. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67079. if (this._shadowMap) {
  67080. this._shadowMap.dispose();
  67081. this._shadowMap = null;
  67082. }
  67083. this._disposeBlurPostProcesses();
  67084. };
  67085. /**
  67086. * Disposes the ShadowGenerator.
  67087. * Returns nothing.
  67088. */
  67089. ShadowGenerator.prototype.dispose = function () {
  67090. this._disposeRTTandPostProcesses();
  67091. if (this._light) {
  67092. this._light._shadowGenerator = null;
  67093. this._light._markMeshesAsLightDirty();
  67094. }
  67095. };
  67096. /**
  67097. * Serializes the shadow generator setup to a json object.
  67098. * @returns The serialized JSON object
  67099. */
  67100. ShadowGenerator.prototype.serialize = function () {
  67101. var serializationObject = {};
  67102. var shadowMap = this.getShadowMap();
  67103. if (!shadowMap) {
  67104. return serializationObject;
  67105. }
  67106. serializationObject.lightId = this._light.id;
  67107. serializationObject.mapSize = shadowMap.getRenderSize();
  67108. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67109. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67110. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67111. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67112. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67113. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67114. serializationObject.depthScale = this.depthScale;
  67115. serializationObject.darkness = this.getDarkness();
  67116. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67117. serializationObject.blurKernel = this.blurKernel;
  67118. serializationObject.blurScale = this.blurScale;
  67119. serializationObject.useKernelBlur = this.useKernelBlur;
  67120. serializationObject.transparencyShadow = this._transparencyShadow;
  67121. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67122. serializationObject.bias = this.bias;
  67123. serializationObject.normalBias = this.normalBias;
  67124. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67125. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67126. serializationObject.filteringQuality = this.filteringQuality;
  67127. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67128. serializationObject.renderList = [];
  67129. if (shadowMap.renderList) {
  67130. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67131. var mesh = shadowMap.renderList[meshIndex];
  67132. serializationObject.renderList.push(mesh.id);
  67133. }
  67134. }
  67135. return serializationObject;
  67136. };
  67137. /**
  67138. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67139. * @param parsedShadowGenerator The JSON object to parse
  67140. * @param scene The scene to create the shadow map for
  67141. * @returns The parsed shadow generator
  67142. */
  67143. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67144. //casting to point light, as light is missing the position attr and typescript complains.
  67145. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67146. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67147. var shadowMap = shadowGenerator.getShadowMap();
  67148. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67149. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67150. meshes.forEach(function (mesh) {
  67151. if (!shadowMap) {
  67152. return;
  67153. }
  67154. if (!shadowMap.renderList) {
  67155. shadowMap.renderList = [];
  67156. }
  67157. shadowMap.renderList.push(mesh);
  67158. });
  67159. }
  67160. if (parsedShadowGenerator.usePoissonSampling) {
  67161. shadowGenerator.usePoissonSampling = true;
  67162. }
  67163. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67164. shadowGenerator.useExponentialShadowMap = true;
  67165. }
  67166. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67167. shadowGenerator.useBlurExponentialShadowMap = true;
  67168. }
  67169. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67170. shadowGenerator.useCloseExponentialShadowMap = true;
  67171. }
  67172. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67173. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67174. }
  67175. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67176. shadowGenerator.usePercentageCloserFiltering = true;
  67177. }
  67178. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67179. shadowGenerator.useContactHardeningShadow = true;
  67180. }
  67181. if (parsedShadowGenerator.filteringQuality) {
  67182. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67183. }
  67184. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67185. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67186. }
  67187. // Backward compat
  67188. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67189. shadowGenerator.useExponentialShadowMap = true;
  67190. }
  67191. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67192. shadowGenerator.useBlurExponentialShadowMap = true;
  67193. }
  67194. if (parsedShadowGenerator.depthScale) {
  67195. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67196. }
  67197. if (parsedShadowGenerator.blurScale) {
  67198. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67199. }
  67200. if (parsedShadowGenerator.blurBoxOffset) {
  67201. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67202. }
  67203. if (parsedShadowGenerator.useKernelBlur) {
  67204. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67205. }
  67206. if (parsedShadowGenerator.blurKernel) {
  67207. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67208. }
  67209. if (parsedShadowGenerator.bias !== undefined) {
  67210. shadowGenerator.bias = parsedShadowGenerator.bias;
  67211. }
  67212. if (parsedShadowGenerator.normalBias !== undefined) {
  67213. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67214. }
  67215. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67216. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67217. }
  67218. if (parsedShadowGenerator.darkness) {
  67219. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67220. }
  67221. if (parsedShadowGenerator.transparencyShadow) {
  67222. shadowGenerator.setTransparencyShadow(true);
  67223. }
  67224. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67225. return shadowGenerator;
  67226. };
  67227. /**
  67228. * Shadow generator mode None: no filtering applied.
  67229. */
  67230. ShadowGenerator.FILTER_NONE = 0;
  67231. /**
  67232. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67233. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67234. */
  67235. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67236. /**
  67237. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67238. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67239. */
  67240. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67241. /**
  67242. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67243. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67244. */
  67245. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67246. /**
  67247. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67248. * edge artifacts on steep falloff.
  67249. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67250. */
  67251. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67252. /**
  67253. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67254. * edge artifacts on steep falloff.
  67255. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67256. */
  67257. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67258. /**
  67259. * Shadow generator mode PCF: Percentage Closer Filtering
  67260. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67261. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67262. */
  67263. ShadowGenerator.FILTER_PCF = 6;
  67264. /**
  67265. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67266. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67267. * Contact Hardening
  67268. */
  67269. ShadowGenerator.FILTER_PCSS = 7;
  67270. /**
  67271. * Reserved for PCF and PCSS
  67272. * Highest Quality.
  67273. *
  67274. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67275. *
  67276. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67277. */
  67278. ShadowGenerator.QUALITY_HIGH = 0;
  67279. /**
  67280. * Reserved for PCF and PCSS
  67281. * Good tradeoff for quality/perf cross devices
  67282. *
  67283. * Execute PCF on a 3*3 kernel.
  67284. *
  67285. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67286. */
  67287. ShadowGenerator.QUALITY_MEDIUM = 1;
  67288. /**
  67289. * Reserved for PCF and PCSS
  67290. * The lowest quality but the fastest.
  67291. *
  67292. * Execute PCF on a 1*1 kernel.
  67293. *
  67294. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67295. */
  67296. ShadowGenerator.QUALITY_LOW = 2;
  67297. return ShadowGenerator;
  67298. }());
  67299. BABYLON.ShadowGenerator = ShadowGenerator;
  67300. })(BABYLON || (BABYLON = {}));
  67301. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67302. var BABYLON;
  67303. (function (BABYLON) {
  67304. var DefaultLoadingScreen = /** @class */ (function () {
  67305. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67306. if (_loadingText === void 0) { _loadingText = ""; }
  67307. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67308. var _this = this;
  67309. this._renderingCanvas = _renderingCanvas;
  67310. this._loadingText = _loadingText;
  67311. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67312. // Resize
  67313. this._resizeLoadingUI = function () {
  67314. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67315. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67316. if (!_this._loadingDiv) {
  67317. return;
  67318. }
  67319. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67320. _this._loadingDiv.style.left = canvasRect.left + "px";
  67321. _this._loadingDiv.style.top = canvasRect.top + "px";
  67322. _this._loadingDiv.style.width = canvasRect.width + "px";
  67323. _this._loadingDiv.style.height = canvasRect.height + "px";
  67324. };
  67325. }
  67326. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67327. if (this._loadingDiv) {
  67328. // Do not add a loading screen if there is already one
  67329. return;
  67330. }
  67331. this._loadingDiv = document.createElement("div");
  67332. this._loadingDiv.id = "babylonjsLoadingDiv";
  67333. this._loadingDiv.style.opacity = "0";
  67334. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67335. this._loadingDiv.style.pointerEvents = "none";
  67336. // Loading text
  67337. this._loadingTextDiv = document.createElement("div");
  67338. this._loadingTextDiv.style.position = "absolute";
  67339. this._loadingTextDiv.style.left = "0";
  67340. this._loadingTextDiv.style.top = "50%";
  67341. this._loadingTextDiv.style.marginTop = "80px";
  67342. this._loadingTextDiv.style.width = "100%";
  67343. this._loadingTextDiv.style.height = "20px";
  67344. this._loadingTextDiv.style.fontFamily = "Arial";
  67345. this._loadingTextDiv.style.fontSize = "14px";
  67346. this._loadingTextDiv.style.color = "white";
  67347. this._loadingTextDiv.style.textAlign = "center";
  67348. this._loadingTextDiv.innerHTML = "Loading";
  67349. this._loadingDiv.appendChild(this._loadingTextDiv);
  67350. //set the predefined text
  67351. this._loadingTextDiv.innerHTML = this._loadingText;
  67352. // Generating keyframes
  67353. var style = document.createElement('style');
  67354. style.type = 'text/css';
  67355. 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 }";
  67356. style.innerHTML = keyFrames;
  67357. document.getElementsByTagName('head')[0].appendChild(style);
  67358. // Loading img
  67359. var imgBack = new Image();
  67360. 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";
  67361. imgBack.style.position = "absolute";
  67362. imgBack.style.left = "50%";
  67363. imgBack.style.top = "50%";
  67364. imgBack.style.marginLeft = "-60px";
  67365. imgBack.style.marginTop = "-60px";
  67366. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67367. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67368. imgBack.style.transformOrigin = "50% 50%";
  67369. imgBack.style.webkitTransformOrigin = "50% 50%";
  67370. this._loadingDiv.appendChild(imgBack);
  67371. this._resizeLoadingUI();
  67372. window.addEventListener("resize", this._resizeLoadingUI);
  67373. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67374. document.body.appendChild(this._loadingDiv);
  67375. this._loadingDiv.style.opacity = "1";
  67376. };
  67377. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67378. var _this = this;
  67379. if (!this._loadingDiv) {
  67380. return;
  67381. }
  67382. var onTransitionEnd = function () {
  67383. if (!_this._loadingDiv) {
  67384. return;
  67385. }
  67386. document.body.removeChild(_this._loadingDiv);
  67387. window.removeEventListener("resize", _this._resizeLoadingUI);
  67388. _this._loadingDiv = null;
  67389. };
  67390. this._loadingDiv.style.opacity = "0";
  67391. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67392. };
  67393. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67394. set: function (text) {
  67395. this._loadingText = text;
  67396. if (this._loadingTextDiv) {
  67397. this._loadingTextDiv.innerHTML = this._loadingText;
  67398. }
  67399. },
  67400. enumerable: true,
  67401. configurable: true
  67402. });
  67403. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67404. get: function () {
  67405. return this._loadingDivBackgroundColor;
  67406. },
  67407. set: function (color) {
  67408. this._loadingDivBackgroundColor = color;
  67409. if (!this._loadingDiv) {
  67410. return;
  67411. }
  67412. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67413. },
  67414. enumerable: true,
  67415. configurable: true
  67416. });
  67417. return DefaultLoadingScreen;
  67418. }());
  67419. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67420. })(BABYLON || (BABYLON = {}));
  67421. //# sourceMappingURL=babylon.loadingScreen.js.map
  67422. var BABYLON;
  67423. (function (BABYLON) {
  67424. var SceneLoaderProgressEvent = /** @class */ (function () {
  67425. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67426. this.lengthComputable = lengthComputable;
  67427. this.loaded = loaded;
  67428. this.total = total;
  67429. }
  67430. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67431. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67432. };
  67433. return SceneLoaderProgressEvent;
  67434. }());
  67435. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67436. var SceneLoader = /** @class */ (function () {
  67437. function SceneLoader() {
  67438. }
  67439. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67440. get: function () {
  67441. return 0;
  67442. },
  67443. enumerable: true,
  67444. configurable: true
  67445. });
  67446. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67447. get: function () {
  67448. return 1;
  67449. },
  67450. enumerable: true,
  67451. configurable: true
  67452. });
  67453. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67454. get: function () {
  67455. return 2;
  67456. },
  67457. enumerable: true,
  67458. configurable: true
  67459. });
  67460. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67461. get: function () {
  67462. return 3;
  67463. },
  67464. enumerable: true,
  67465. configurable: true
  67466. });
  67467. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67468. get: function () {
  67469. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67470. },
  67471. set: function (value) {
  67472. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67473. },
  67474. enumerable: true,
  67475. configurable: true
  67476. });
  67477. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67478. get: function () {
  67479. return SceneLoader._ShowLoadingScreen;
  67480. },
  67481. set: function (value) {
  67482. SceneLoader._ShowLoadingScreen = value;
  67483. },
  67484. enumerable: true,
  67485. configurable: true
  67486. });
  67487. Object.defineProperty(SceneLoader, "loggingLevel", {
  67488. get: function () {
  67489. return SceneLoader._loggingLevel;
  67490. },
  67491. set: function (value) {
  67492. SceneLoader._loggingLevel = value;
  67493. },
  67494. enumerable: true,
  67495. configurable: true
  67496. });
  67497. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67498. get: function () {
  67499. return SceneLoader._CleanBoneMatrixWeights;
  67500. },
  67501. set: function (value) {
  67502. SceneLoader._CleanBoneMatrixWeights = value;
  67503. },
  67504. enumerable: true,
  67505. configurable: true
  67506. });
  67507. SceneLoader._getDefaultPlugin = function () {
  67508. return SceneLoader._registeredPlugins[".babylon"];
  67509. };
  67510. SceneLoader._getPluginForExtension = function (extension) {
  67511. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67512. if (registeredPlugin) {
  67513. return registeredPlugin;
  67514. }
  67515. 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");
  67516. return SceneLoader._getDefaultPlugin();
  67517. };
  67518. SceneLoader._getPluginForDirectLoad = function (data) {
  67519. for (var extension in SceneLoader._registeredPlugins) {
  67520. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67521. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67522. return SceneLoader._registeredPlugins[extension];
  67523. }
  67524. }
  67525. return SceneLoader._getDefaultPlugin();
  67526. };
  67527. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67528. if (sceneFilename.name) {
  67529. sceneFilename = sceneFilename.name;
  67530. }
  67531. var queryStringPosition = sceneFilename.indexOf("?");
  67532. if (queryStringPosition !== -1) {
  67533. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67534. }
  67535. var dotPosition = sceneFilename.lastIndexOf(".");
  67536. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67537. return SceneLoader._getPluginForExtension(extension);
  67538. };
  67539. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67540. SceneLoader._getDirectLoad = function (sceneFilename) {
  67541. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67542. return sceneFilename.substr(5);
  67543. }
  67544. return null;
  67545. };
  67546. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67547. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67548. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67549. var plugin;
  67550. if (registeredPlugin.plugin.createPlugin) {
  67551. plugin = registeredPlugin.plugin.createPlugin();
  67552. }
  67553. else {
  67554. plugin = registeredPlugin.plugin;
  67555. }
  67556. var useArrayBuffer = registeredPlugin.isBinary;
  67557. var database;
  67558. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67559. var dataCallback = function (data, responseURL) {
  67560. if (scene.isDisposed) {
  67561. onError("Scene has been disposed");
  67562. return;
  67563. }
  67564. scene.database = database;
  67565. onSuccess(plugin, data, responseURL);
  67566. };
  67567. var request = null;
  67568. var pluginDisposed = false;
  67569. var onDisposeObservable = plugin.onDisposeObservable;
  67570. if (onDisposeObservable) {
  67571. onDisposeObservable.add(function () {
  67572. pluginDisposed = true;
  67573. if (request) {
  67574. request.abort();
  67575. request = null;
  67576. }
  67577. onDispose();
  67578. });
  67579. }
  67580. var manifestChecked = function () {
  67581. if (pluginDisposed) {
  67582. return;
  67583. }
  67584. var url = rootUrl + sceneFilename;
  67585. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67586. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67587. } : undefined, database, useArrayBuffer, function (request, exception) {
  67588. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67589. });
  67590. };
  67591. if (directLoad) {
  67592. dataCallback(directLoad);
  67593. return plugin;
  67594. }
  67595. if (rootUrl.indexOf("file:") === -1) {
  67596. var engine = scene.getEngine();
  67597. var canUseOfflineSupport = engine.enableOfflineSupport;
  67598. if (canUseOfflineSupport) {
  67599. // Also check for exceptions
  67600. var exceptionFound = false;
  67601. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67602. var regex = _a[_i];
  67603. if (regex.test(rootUrl + sceneFilename)) {
  67604. exceptionFound = true;
  67605. break;
  67606. }
  67607. }
  67608. canUseOfflineSupport = !exceptionFound;
  67609. }
  67610. if (canUseOfflineSupport) {
  67611. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67612. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67613. }
  67614. else {
  67615. manifestChecked();
  67616. }
  67617. }
  67618. // Loading file from disk via input file or drag'n'drop
  67619. else {
  67620. var fileOrString = sceneFilename;
  67621. if (fileOrString.name) { // File
  67622. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67623. }
  67624. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67625. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67626. }
  67627. else {
  67628. onError("Unable to find file named " + sceneFilename);
  67629. }
  67630. }
  67631. return plugin;
  67632. };
  67633. // Public functions
  67634. SceneLoader.GetPluginForExtension = function (extension) {
  67635. return SceneLoader._getPluginForExtension(extension).plugin;
  67636. };
  67637. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67638. return !!SceneLoader._registeredPlugins[extension];
  67639. };
  67640. SceneLoader.RegisterPlugin = function (plugin) {
  67641. if (typeof plugin.extensions === "string") {
  67642. var extension = plugin.extensions;
  67643. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67644. plugin: plugin,
  67645. isBinary: false
  67646. };
  67647. }
  67648. else {
  67649. var extensions = plugin.extensions;
  67650. Object.keys(extensions).forEach(function (extension) {
  67651. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67652. plugin: plugin,
  67653. isBinary: extensions[extension].isBinary
  67654. };
  67655. });
  67656. }
  67657. };
  67658. /**
  67659. * Import meshes into a scene
  67660. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67661. * @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)
  67662. * @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)
  67663. * @param scene the instance of BABYLON.Scene to append to
  67664. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67665. * @param onProgress a callback with a progress event for each file being loaded
  67666. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67667. * @param pluginExtension the extension used to determine the plugin
  67668. * @returns The loaded plugin
  67669. */
  67670. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67671. if (sceneFilename === void 0) { sceneFilename = ""; }
  67672. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67673. if (onSuccess === void 0) { onSuccess = null; }
  67674. if (onProgress === void 0) { onProgress = null; }
  67675. if (onError === void 0) { onError = null; }
  67676. if (pluginExtension === void 0) { pluginExtension = null; }
  67677. if (!scene) {
  67678. BABYLON.Tools.Error("No scene available to import mesh to");
  67679. return null;
  67680. }
  67681. if (!sceneFilename) {
  67682. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67683. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67684. }
  67685. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67686. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67687. return null;
  67688. }
  67689. var loadingToken = {};
  67690. scene._addPendingData(loadingToken);
  67691. var disposeHandler = function () {
  67692. scene._removePendingData(loadingToken);
  67693. };
  67694. var errorHandler = function (message, exception) {
  67695. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67696. if (onError) {
  67697. onError(scene, errorMessage, exception);
  67698. }
  67699. else {
  67700. BABYLON.Tools.Error(errorMessage);
  67701. // should the exception be thrown?
  67702. }
  67703. disposeHandler();
  67704. };
  67705. var progressHandler = onProgress ? function (event) {
  67706. try {
  67707. onProgress(event);
  67708. }
  67709. catch (e) {
  67710. errorHandler("Error in onProgress callback", e);
  67711. }
  67712. } : undefined;
  67713. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67714. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67715. if (onSuccess) {
  67716. try {
  67717. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67718. }
  67719. catch (e) {
  67720. errorHandler("Error in onSuccess callback", e);
  67721. }
  67722. }
  67723. scene._removePendingData(loadingToken);
  67724. };
  67725. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67726. if (plugin.rewriteRootURL) {
  67727. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67728. }
  67729. if (sceneFilename === "") {
  67730. if (sceneFilename === "") {
  67731. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67732. }
  67733. }
  67734. if (plugin.importMesh) {
  67735. var syncedPlugin = plugin;
  67736. var meshes = new Array();
  67737. var particleSystems = new Array();
  67738. var skeletons = new Array();
  67739. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67740. return;
  67741. }
  67742. scene.loadingPluginName = plugin.name;
  67743. successHandler(meshes, particleSystems, skeletons, []);
  67744. }
  67745. else {
  67746. var asyncedPlugin = plugin;
  67747. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67748. scene.loadingPluginName = plugin.name;
  67749. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67750. }).catch(function (error) {
  67751. errorHandler(error.message, error);
  67752. });
  67753. }
  67754. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67755. };
  67756. /**
  67757. * Import meshes into a scene
  67758. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67759. * @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)
  67760. * @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)
  67761. * @param scene the instance of BABYLON.Scene to append to
  67762. * @param onProgress a callback with a progress event for each file being loaded
  67763. * @param pluginExtension the extension used to determine the plugin
  67764. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67765. */
  67766. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67767. if (sceneFilename === void 0) { sceneFilename = ""; }
  67768. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67769. if (onProgress === void 0) { onProgress = null; }
  67770. if (pluginExtension === void 0) { pluginExtension = null; }
  67771. return new Promise(function (resolve, reject) {
  67772. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67773. resolve({
  67774. meshes: meshes,
  67775. particleSystems: particleSystems,
  67776. skeletons: skeletons,
  67777. animationGroups: animationGroups
  67778. });
  67779. }, onProgress, function (scene, message, exception) {
  67780. reject(exception || new Error(message));
  67781. }, pluginExtension);
  67782. });
  67783. };
  67784. /**
  67785. * Load a scene
  67786. * @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)
  67787. * @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)
  67788. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67789. * @param onSuccess a callback with the scene when import succeeds
  67790. * @param onProgress a callback with a progress event for each file being loaded
  67791. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67792. * @param pluginExtension the extension used to determine the plugin
  67793. * @returns The loaded plugin
  67794. */
  67795. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67796. if (onSuccess === void 0) { onSuccess = null; }
  67797. if (onProgress === void 0) { onProgress = null; }
  67798. if (onError === void 0) { onError = null; }
  67799. if (pluginExtension === void 0) { pluginExtension = null; }
  67800. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67801. };
  67802. /**
  67803. * Load a scene
  67804. * @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)
  67805. * @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)
  67806. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67807. * @param onProgress a callback with a progress event for each file being loaded
  67808. * @param pluginExtension the extension used to determine the plugin
  67809. * @returns The loaded scene
  67810. */
  67811. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67812. if (onProgress === void 0) { onProgress = null; }
  67813. if (pluginExtension === void 0) { pluginExtension = null; }
  67814. return new Promise(function (resolve, reject) {
  67815. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67816. resolve(scene);
  67817. }, onProgress, function (scene, message, exception) {
  67818. reject(exception || new Error(message));
  67819. }, pluginExtension);
  67820. });
  67821. };
  67822. /**
  67823. * Append a scene
  67824. * @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)
  67825. * @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)
  67826. * @param scene is the instance of BABYLON.Scene to append to
  67827. * @param onSuccess a callback with the scene when import succeeds
  67828. * @param onProgress a callback with a progress event for each file being loaded
  67829. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67830. * @param pluginExtension the extension used to determine the plugin
  67831. * @returns The loaded plugin
  67832. */
  67833. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67834. if (sceneFilename === void 0) { sceneFilename = ""; }
  67835. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67836. if (onSuccess === void 0) { onSuccess = null; }
  67837. if (onProgress === void 0) { onProgress = null; }
  67838. if (onError === void 0) { onError = null; }
  67839. if (pluginExtension === void 0) { pluginExtension = null; }
  67840. if (!scene) {
  67841. BABYLON.Tools.Error("No scene available to append to");
  67842. return null;
  67843. }
  67844. if (!sceneFilename) {
  67845. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67846. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67847. }
  67848. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67849. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67850. return null;
  67851. }
  67852. if (SceneLoader.ShowLoadingScreen) {
  67853. scene.getEngine().displayLoadingUI();
  67854. }
  67855. var loadingToken = {};
  67856. scene._addPendingData(loadingToken);
  67857. var disposeHandler = function () {
  67858. scene._removePendingData(loadingToken);
  67859. scene.getEngine().hideLoadingUI();
  67860. };
  67861. var errorHandler = function (message, exception) {
  67862. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67863. if (onError) {
  67864. onError(scene, errorMessage, exception);
  67865. }
  67866. else {
  67867. BABYLON.Tools.Error(errorMessage);
  67868. // should the exception be thrown?
  67869. }
  67870. disposeHandler();
  67871. };
  67872. var progressHandler = onProgress ? function (event) {
  67873. try {
  67874. onProgress(event);
  67875. }
  67876. catch (e) {
  67877. errorHandler("Error in onProgress callback", e);
  67878. }
  67879. } : undefined;
  67880. var successHandler = function () {
  67881. if (onSuccess) {
  67882. try {
  67883. onSuccess(scene);
  67884. }
  67885. catch (e) {
  67886. errorHandler("Error in onSuccess callback", e);
  67887. }
  67888. }
  67889. scene._removePendingData(loadingToken);
  67890. };
  67891. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67892. if (sceneFilename === "") {
  67893. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67894. }
  67895. if (plugin.load) {
  67896. var syncedPlugin = plugin;
  67897. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67898. return;
  67899. }
  67900. scene.loadingPluginName = plugin.name;
  67901. successHandler();
  67902. }
  67903. else {
  67904. var asyncedPlugin = plugin;
  67905. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67906. scene.loadingPluginName = plugin.name;
  67907. successHandler();
  67908. }).catch(function (error) {
  67909. errorHandler(error.message, error);
  67910. });
  67911. }
  67912. if (SceneLoader.ShowLoadingScreen) {
  67913. scene.executeWhenReady(function () {
  67914. scene.getEngine().hideLoadingUI();
  67915. });
  67916. }
  67917. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67918. };
  67919. /**
  67920. * Append a scene
  67921. * @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)
  67922. * @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)
  67923. * @param scene is the instance of BABYLON.Scene to append to
  67924. * @param onProgress a callback with a progress event for each file being loaded
  67925. * @param pluginExtension the extension used to determine the plugin
  67926. * @returns The given scene
  67927. */
  67928. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67929. if (sceneFilename === void 0) { sceneFilename = ""; }
  67930. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67931. if (onProgress === void 0) { onProgress = null; }
  67932. if (pluginExtension === void 0) { pluginExtension = null; }
  67933. return new Promise(function (resolve, reject) {
  67934. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67935. resolve(scene);
  67936. }, onProgress, function (scene, message, exception) {
  67937. reject(exception || new Error(message));
  67938. }, pluginExtension);
  67939. });
  67940. };
  67941. /**
  67942. * Load a scene into an asset container
  67943. * @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)
  67944. * @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)
  67945. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67946. * @param onSuccess a callback with the scene when import succeeds
  67947. * @param onProgress a callback with a progress event for each file being loaded
  67948. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67949. * @param pluginExtension the extension used to determine the plugin
  67950. * @returns The loaded plugin
  67951. */
  67952. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67953. if (sceneFilename === void 0) { sceneFilename = ""; }
  67954. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67955. if (onSuccess === void 0) { onSuccess = null; }
  67956. if (onProgress === void 0) { onProgress = null; }
  67957. if (onError === void 0) { onError = null; }
  67958. if (pluginExtension === void 0) { pluginExtension = null; }
  67959. if (!scene) {
  67960. BABYLON.Tools.Error("No scene available to load asset container to");
  67961. return null;
  67962. }
  67963. if (!sceneFilename) {
  67964. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67965. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67966. }
  67967. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67968. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67969. return null;
  67970. }
  67971. var loadingToken = {};
  67972. scene._addPendingData(loadingToken);
  67973. var disposeHandler = function () {
  67974. scene._removePendingData(loadingToken);
  67975. };
  67976. var errorHandler = function (message, exception) {
  67977. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67978. if (onError) {
  67979. onError(scene, errorMessage, exception);
  67980. }
  67981. else {
  67982. BABYLON.Tools.Error(errorMessage);
  67983. // should the exception be thrown?
  67984. }
  67985. disposeHandler();
  67986. };
  67987. var progressHandler = onProgress ? function (event) {
  67988. try {
  67989. onProgress(event);
  67990. }
  67991. catch (e) {
  67992. errorHandler("Error in onProgress callback", e);
  67993. }
  67994. } : undefined;
  67995. var successHandler = function (assets) {
  67996. if (onSuccess) {
  67997. try {
  67998. onSuccess(assets);
  67999. }
  68000. catch (e) {
  68001. errorHandler("Error in onSuccess callback", e);
  68002. }
  68003. }
  68004. scene._removePendingData(loadingToken);
  68005. };
  68006. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68007. if (plugin.loadAssetContainer) {
  68008. var syncedPlugin = plugin;
  68009. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68010. if (!assetContainer) {
  68011. return;
  68012. }
  68013. scene.loadingPluginName = plugin.name;
  68014. successHandler(assetContainer);
  68015. }
  68016. else if (plugin.loadAssetContainerAsync) {
  68017. var asyncedPlugin = plugin;
  68018. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68019. scene.loadingPluginName = plugin.name;
  68020. successHandler(assetContainer);
  68021. }).catch(function (error) {
  68022. errorHandler(error.message, error);
  68023. });
  68024. }
  68025. else {
  68026. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68027. }
  68028. if (SceneLoader.ShowLoadingScreen) {
  68029. scene.executeWhenReady(function () {
  68030. scene.getEngine().hideLoadingUI();
  68031. });
  68032. }
  68033. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68034. };
  68035. /**
  68036. * Load a scene into an asset container
  68037. * @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)
  68038. * @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)
  68039. * @param scene is the instance of BABYLON.Scene to append to
  68040. * @param onProgress a callback with a progress event for each file being loaded
  68041. * @param pluginExtension the extension used to determine the plugin
  68042. * @returns The loaded asset container
  68043. */
  68044. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68045. if (sceneFilename === void 0) { sceneFilename = ""; }
  68046. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68047. if (onProgress === void 0) { onProgress = null; }
  68048. if (pluginExtension === void 0) { pluginExtension = null; }
  68049. return new Promise(function (resolve, reject) {
  68050. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68051. resolve(assetContainer);
  68052. }, onProgress, function (scene, message, exception) {
  68053. reject(exception || new Error(message));
  68054. }, pluginExtension);
  68055. });
  68056. };
  68057. // Flags
  68058. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68059. SceneLoader._ShowLoadingScreen = true;
  68060. SceneLoader._CleanBoneMatrixWeights = false;
  68061. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68062. // Members
  68063. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68064. SceneLoader._registeredPlugins = {};
  68065. return SceneLoader;
  68066. }());
  68067. BABYLON.SceneLoader = SceneLoader;
  68068. ;
  68069. })(BABYLON || (BABYLON = {}));
  68070. //# sourceMappingURL=babylon.sceneLoader.js.map
  68071. var BABYLON;
  68072. (function (BABYLON) {
  68073. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68074. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68075. var parsedMaterial = parsedData.materials[index];
  68076. if (parsedMaterial.id === id) {
  68077. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68078. }
  68079. }
  68080. return null;
  68081. };
  68082. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68083. for (var i in names) {
  68084. if (mesh.name === names[i]) {
  68085. hierarchyIds.push(mesh.id);
  68086. return true;
  68087. }
  68088. }
  68089. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68090. hierarchyIds.push(mesh.id);
  68091. return true;
  68092. }
  68093. return false;
  68094. };
  68095. var logOperation = function (operation, producer) {
  68096. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68097. };
  68098. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68099. if (addToScene === void 0) { addToScene = false; }
  68100. var container = new BABYLON.AssetContainer(scene);
  68101. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68102. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68103. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68104. // and avoid problems with multiple concurrent .babylon loads.
  68105. var log = "importScene has failed JSON parse";
  68106. try {
  68107. var parsedData = JSON.parse(data);
  68108. log = "";
  68109. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68110. var index;
  68111. var cache;
  68112. // Lights
  68113. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68114. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68115. var parsedLight = parsedData.lights[index];
  68116. var light = BABYLON.Light.Parse(parsedLight, scene);
  68117. if (light) {
  68118. container.lights.push(light);
  68119. log += (index === 0 ? "\n\tLights:" : "");
  68120. log += "\n\t\t" + light.toString(fullDetails);
  68121. }
  68122. }
  68123. }
  68124. // Animations
  68125. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68126. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68127. var parsedAnimation = parsedData.animations[index];
  68128. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68129. scene.animations.push(animation);
  68130. container.animations.push(animation);
  68131. log += (index === 0 ? "\n\tAnimations:" : "");
  68132. log += "\n\t\t" + animation.toString(fullDetails);
  68133. }
  68134. }
  68135. // Materials
  68136. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68137. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68138. var parsedMaterial = parsedData.materials[index];
  68139. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68140. container.materials.push(mat);
  68141. log += (index === 0 ? "\n\tMaterials:" : "");
  68142. log += "\n\t\t" + mat.toString(fullDetails);
  68143. }
  68144. }
  68145. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68146. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68147. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68148. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68149. container.multiMaterials.push(mmat);
  68150. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68151. log += "\n\t\t" + mmat.toString(fullDetails);
  68152. }
  68153. }
  68154. // Morph targets
  68155. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68156. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68157. var managerData = _a[_i];
  68158. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68159. }
  68160. }
  68161. // Skeletons
  68162. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68163. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68164. var parsedSkeleton = parsedData.skeletons[index];
  68165. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68166. container.skeletons.push(skeleton);
  68167. log += (index === 0 ? "\n\tSkeletons:" : "");
  68168. log += "\n\t\t" + skeleton.toString(fullDetails);
  68169. }
  68170. }
  68171. // Geometries
  68172. var geometries = parsedData.geometries;
  68173. if (geometries !== undefined && geometries !== null) {
  68174. var addedGeometry = new Array();
  68175. // Boxes
  68176. var boxes = geometries.boxes;
  68177. if (boxes !== undefined && boxes !== null) {
  68178. for (index = 0, cache = boxes.length; index < cache; index++) {
  68179. var parsedBox = boxes[index];
  68180. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68181. }
  68182. }
  68183. // Spheres
  68184. var spheres = geometries.spheres;
  68185. if (spheres !== undefined && spheres !== null) {
  68186. for (index = 0, cache = spheres.length; index < cache; index++) {
  68187. var parsedSphere = spheres[index];
  68188. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68189. }
  68190. }
  68191. // Cylinders
  68192. var cylinders = geometries.cylinders;
  68193. if (cylinders !== undefined && cylinders !== null) {
  68194. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68195. var parsedCylinder = cylinders[index];
  68196. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68197. }
  68198. }
  68199. // Toruses
  68200. var toruses = geometries.toruses;
  68201. if (toruses !== undefined && toruses !== null) {
  68202. for (index = 0, cache = toruses.length; index < cache; index++) {
  68203. var parsedTorus = toruses[index];
  68204. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68205. }
  68206. }
  68207. // Grounds
  68208. var grounds = geometries.grounds;
  68209. if (grounds !== undefined && grounds !== null) {
  68210. for (index = 0, cache = grounds.length; index < cache; index++) {
  68211. var parsedGround = grounds[index];
  68212. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68213. }
  68214. }
  68215. // Planes
  68216. var planes = geometries.planes;
  68217. if (planes !== undefined && planes !== null) {
  68218. for (index = 0, cache = planes.length; index < cache; index++) {
  68219. var parsedPlane = planes[index];
  68220. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68221. }
  68222. }
  68223. // TorusKnots
  68224. var torusKnots = geometries.torusKnots;
  68225. if (torusKnots !== undefined && torusKnots !== null) {
  68226. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68227. var parsedTorusKnot = torusKnots[index];
  68228. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68229. }
  68230. }
  68231. // VertexData
  68232. var vertexData = geometries.vertexData;
  68233. if (vertexData !== undefined && vertexData !== null) {
  68234. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68235. var parsedVertexData = vertexData[index];
  68236. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68237. }
  68238. }
  68239. addedGeometry.forEach(function (g) {
  68240. if (g) {
  68241. container.geometries.push(g);
  68242. }
  68243. });
  68244. }
  68245. // Transform nodes
  68246. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68247. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68248. var parsedTransformNode = parsedData.transformNodes[index];
  68249. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68250. container.transformNodes.push(node);
  68251. }
  68252. }
  68253. // Meshes
  68254. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68255. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68256. var parsedMesh = parsedData.meshes[index];
  68257. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68258. container.meshes.push(mesh);
  68259. log += (index === 0 ? "\n\tMeshes:" : "");
  68260. log += "\n\t\t" + mesh.toString(fullDetails);
  68261. }
  68262. }
  68263. // Cameras
  68264. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68265. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68266. var parsedCamera = parsedData.cameras[index];
  68267. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68268. container.cameras.push(camera);
  68269. log += (index === 0 ? "\n\tCameras:" : "");
  68270. log += "\n\t\t" + camera.toString(fullDetails);
  68271. }
  68272. }
  68273. // Browsing all the graph to connect the dots
  68274. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68275. var camera = scene.cameras[index];
  68276. if (camera._waitingParentId) {
  68277. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68278. camera._waitingParentId = null;
  68279. }
  68280. }
  68281. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68282. var light_1 = scene.lights[index];
  68283. if (light_1 && light_1._waitingParentId) {
  68284. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68285. light_1._waitingParentId = null;
  68286. }
  68287. }
  68288. // Sounds
  68289. // TODO: add sound
  68290. var loadedSounds = [];
  68291. var loadedSound;
  68292. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68293. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68294. var parsedSound = parsedData.sounds[index];
  68295. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68296. if (!parsedSound.url)
  68297. parsedSound.url = parsedSound.name;
  68298. if (!loadedSounds[parsedSound.url]) {
  68299. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68300. loadedSounds[parsedSound.url] = loadedSound;
  68301. container.sounds.push(loadedSound);
  68302. }
  68303. else {
  68304. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68305. }
  68306. }
  68307. else {
  68308. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68309. }
  68310. }
  68311. }
  68312. loadedSounds = [];
  68313. // Connect parents & children and parse actions
  68314. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68315. var transformNode = scene.transformNodes[index];
  68316. if (transformNode._waitingParentId) {
  68317. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68318. transformNode._waitingParentId = null;
  68319. }
  68320. }
  68321. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68322. var mesh = scene.meshes[index];
  68323. if (mesh._waitingParentId) {
  68324. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68325. mesh._waitingParentId = null;
  68326. }
  68327. if (mesh._waitingActions) {
  68328. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68329. mesh._waitingActions = null;
  68330. }
  68331. }
  68332. // freeze world matrix application
  68333. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68334. var currentMesh = scene.meshes[index];
  68335. if (currentMesh._waitingFreezeWorldMatrix) {
  68336. currentMesh.freezeWorldMatrix();
  68337. currentMesh._waitingFreezeWorldMatrix = null;
  68338. }
  68339. else {
  68340. currentMesh.computeWorldMatrix(true);
  68341. }
  68342. }
  68343. // Particles Systems
  68344. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68345. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68346. var parsedParticleSystem = parsedData.particleSystems[index];
  68347. if (parsedParticleSystem.activeParticleCount) {
  68348. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68349. container.particleSystems.push(ps);
  68350. }
  68351. else {
  68352. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68353. container.particleSystems.push(ps);
  68354. }
  68355. }
  68356. }
  68357. // Lens flares
  68358. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68359. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68360. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68361. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68362. container.lensFlareSystems.push(lf);
  68363. }
  68364. }
  68365. // Shadows
  68366. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68367. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68368. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68369. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68370. container.shadowGenerators.push(sg);
  68371. }
  68372. }
  68373. // Lights exclusions / inclusions
  68374. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68375. var light_2 = scene.lights[index];
  68376. // Excluded check
  68377. if (light_2._excludedMeshesIds.length > 0) {
  68378. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68379. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68380. if (excludedMesh) {
  68381. light_2.excludedMeshes.push(excludedMesh);
  68382. }
  68383. }
  68384. light_2._excludedMeshesIds = [];
  68385. }
  68386. // Included check
  68387. if (light_2._includedOnlyMeshesIds.length > 0) {
  68388. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68389. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68390. if (includedOnlyMesh) {
  68391. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68392. }
  68393. }
  68394. light_2._includedOnlyMeshesIds = [];
  68395. }
  68396. }
  68397. // Effect layers
  68398. if (parsedData.effectLayers) {
  68399. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68400. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68401. container.effectLayers.push(effectLayer);
  68402. }
  68403. }
  68404. // Actions (scene)
  68405. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68406. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68407. }
  68408. if (!addToScene) {
  68409. container.removeAllFromScene();
  68410. }
  68411. }
  68412. catch (err) {
  68413. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68414. if (onError) {
  68415. onError(msg, err);
  68416. }
  68417. else {
  68418. BABYLON.Tools.Log(msg);
  68419. throw err;
  68420. }
  68421. }
  68422. finally {
  68423. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68424. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68425. }
  68426. }
  68427. return container;
  68428. };
  68429. BABYLON.SceneLoader.RegisterPlugin({
  68430. name: "babylon.js",
  68431. extensions: ".babylon",
  68432. canDirectLoad: function (data) {
  68433. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68434. return true;
  68435. }
  68436. return false;
  68437. },
  68438. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68439. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68440. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68441. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68442. // and avoid problems with multiple concurrent .babylon loads.
  68443. var log = "importMesh has failed JSON parse";
  68444. try {
  68445. var parsedData = JSON.parse(data);
  68446. log = "";
  68447. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68448. if (!meshesNames) {
  68449. meshesNames = null;
  68450. }
  68451. else if (!Array.isArray(meshesNames)) {
  68452. meshesNames = [meshesNames];
  68453. }
  68454. var hierarchyIds = new Array();
  68455. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68456. var loadedSkeletonsIds = [];
  68457. var loadedMaterialsIds = [];
  68458. var index;
  68459. var cache;
  68460. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68461. var parsedMesh = parsedData.meshes[index];
  68462. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68463. if (meshesNames !== null) {
  68464. // Remove found mesh name from list.
  68465. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68466. }
  68467. //Geometry?
  68468. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68469. //does the file contain geometries?
  68470. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68471. //find the correct geometry and add it to the scene
  68472. var found = false;
  68473. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68474. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68475. return;
  68476. }
  68477. else {
  68478. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68479. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68480. switch (geometryType) {
  68481. case "boxes":
  68482. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68483. break;
  68484. case "spheres":
  68485. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68486. break;
  68487. case "cylinders":
  68488. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68489. break;
  68490. case "toruses":
  68491. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68492. break;
  68493. case "grounds":
  68494. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68495. break;
  68496. case "planes":
  68497. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68498. break;
  68499. case "torusKnots":
  68500. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68501. break;
  68502. case "vertexData":
  68503. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68504. break;
  68505. }
  68506. found = true;
  68507. }
  68508. });
  68509. }
  68510. });
  68511. if (found === false) {
  68512. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68513. }
  68514. }
  68515. }
  68516. // Material ?
  68517. if (parsedMesh.materialId) {
  68518. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68519. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68520. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68521. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68522. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68523. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68524. var subMatId = parsedMultiMaterial.materials[matIndex];
  68525. loadedMaterialsIds.push(subMatId);
  68526. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68527. if (mat) {
  68528. log += "\n\tMaterial " + mat.toString(fullDetails);
  68529. }
  68530. }
  68531. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68532. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68533. if (mmat) {
  68534. materialFound = true;
  68535. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68536. }
  68537. break;
  68538. }
  68539. }
  68540. }
  68541. if (materialFound === false) {
  68542. loadedMaterialsIds.push(parsedMesh.materialId);
  68543. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68544. if (!mat) {
  68545. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68546. }
  68547. else {
  68548. log += "\n\tMaterial " + mat.toString(fullDetails);
  68549. }
  68550. }
  68551. }
  68552. // Skeleton ?
  68553. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68554. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68555. if (skeletonAlreadyLoaded === false) {
  68556. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68557. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68558. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68559. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68560. skeletons.push(skeleton);
  68561. loadedSkeletonsIds.push(parsedSkeleton.id);
  68562. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68563. }
  68564. }
  68565. }
  68566. }
  68567. // Morph targets ?
  68568. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68569. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68570. var managerData = _a[_i];
  68571. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68572. }
  68573. }
  68574. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68575. meshes.push(mesh);
  68576. log += "\n\tMesh " + mesh.toString(fullDetails);
  68577. }
  68578. }
  68579. // Connecting parents
  68580. var currentMesh;
  68581. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68582. currentMesh = scene.meshes[index];
  68583. if (currentMesh._waitingParentId) {
  68584. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68585. currentMesh._waitingParentId = null;
  68586. }
  68587. }
  68588. // freeze and compute world matrix application
  68589. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68590. currentMesh = scene.meshes[index];
  68591. if (currentMesh._waitingFreezeWorldMatrix) {
  68592. currentMesh.freezeWorldMatrix();
  68593. currentMesh._waitingFreezeWorldMatrix = null;
  68594. }
  68595. else {
  68596. currentMesh.computeWorldMatrix(true);
  68597. }
  68598. }
  68599. }
  68600. // Particles
  68601. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68602. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68603. var parsedParticleSystem = parsedData.particleSystems[index];
  68604. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68605. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68606. }
  68607. }
  68608. }
  68609. return true;
  68610. }
  68611. catch (err) {
  68612. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68613. if (onError) {
  68614. onError(msg, err);
  68615. }
  68616. else {
  68617. BABYLON.Tools.Log(msg);
  68618. throw err;
  68619. }
  68620. }
  68621. finally {
  68622. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68623. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68624. }
  68625. }
  68626. return false;
  68627. },
  68628. load: function (scene, data, rootUrl, onError) {
  68629. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68630. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68631. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68632. // and avoid problems with multiple concurrent .babylon loads.
  68633. var log = "importScene has failed JSON parse";
  68634. try {
  68635. var parsedData = JSON.parse(data);
  68636. log = "";
  68637. // Scene
  68638. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68639. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68640. }
  68641. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68642. scene.autoClear = parsedData.autoClear;
  68643. }
  68644. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68645. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68646. }
  68647. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68648. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68649. }
  68650. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68651. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68652. }
  68653. // Fog
  68654. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68655. scene.fogMode = parsedData.fogMode;
  68656. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68657. scene.fogStart = parsedData.fogStart;
  68658. scene.fogEnd = parsedData.fogEnd;
  68659. scene.fogDensity = parsedData.fogDensity;
  68660. log += "\tFog mode for scene: ";
  68661. switch (scene.fogMode) {
  68662. // getters not compiling, so using hardcoded
  68663. case 1:
  68664. log += "exp\n";
  68665. break;
  68666. case 2:
  68667. log += "exp2\n";
  68668. break;
  68669. case 3:
  68670. log += "linear\n";
  68671. break;
  68672. }
  68673. }
  68674. //Physics
  68675. if (parsedData.physicsEnabled) {
  68676. var physicsPlugin;
  68677. if (parsedData.physicsEngine === "cannon") {
  68678. physicsPlugin = new BABYLON.CannonJSPlugin();
  68679. }
  68680. else if (parsedData.physicsEngine === "oimo") {
  68681. physicsPlugin = new BABYLON.OimoJSPlugin();
  68682. }
  68683. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68684. //else - default engine, which is currently oimo
  68685. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68686. scene.enablePhysics(physicsGravity, physicsPlugin);
  68687. }
  68688. // Metadata
  68689. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68690. scene.metadata = parsedData.metadata;
  68691. }
  68692. //collisions, if defined. otherwise, default is true
  68693. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68694. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68695. }
  68696. scene.workerCollisions = !!parsedData.workerCollisions;
  68697. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68698. if (!container) {
  68699. return false;
  68700. }
  68701. if (parsedData.autoAnimate) {
  68702. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68703. }
  68704. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68705. scene.setActiveCameraByID(parsedData.activeCameraID);
  68706. }
  68707. // Environment texture
  68708. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68709. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68710. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68711. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68712. if (parsedData.environmentTextureRotationY) {
  68713. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68714. }
  68715. scene.environmentTexture = hdrTexture;
  68716. }
  68717. else {
  68718. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68719. if (parsedData.environmentTextureRotationY) {
  68720. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68721. }
  68722. scene.environmentTexture = cubeTexture;
  68723. }
  68724. if (parsedData.createDefaultSkybox === true) {
  68725. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68726. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68727. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68728. }
  68729. }
  68730. // Finish
  68731. return true;
  68732. }
  68733. catch (err) {
  68734. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68735. if (onError) {
  68736. onError(msg, err);
  68737. }
  68738. else {
  68739. BABYLON.Tools.Log(msg);
  68740. throw err;
  68741. }
  68742. }
  68743. finally {
  68744. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68745. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68746. }
  68747. }
  68748. return false;
  68749. },
  68750. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68751. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68752. return container;
  68753. }
  68754. });
  68755. })(BABYLON || (BABYLON = {}));
  68756. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68757. var BABYLON;
  68758. (function (BABYLON) {
  68759. var FilesInput = /** @class */ (function () {
  68760. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68761. this.onProcessFileCallback = function () { return true; };
  68762. this._engine = engine;
  68763. this._currentScene = scene;
  68764. this._sceneLoadedCallback = sceneLoadedCallback;
  68765. this._progressCallback = progressCallback;
  68766. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68767. this._textureLoadingCallback = textureLoadingCallback;
  68768. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68769. this._onReloadCallback = onReloadCallback;
  68770. this._errorCallback = errorCallback;
  68771. }
  68772. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68773. var _this = this;
  68774. if (elementToMonitor) {
  68775. this._elementToMonitor = elementToMonitor;
  68776. this._dragEnterHandler = function (e) { _this.drag(e); };
  68777. this._dragOverHandler = function (e) { _this.drag(e); };
  68778. this._dropHandler = function (e) { _this.drop(e); };
  68779. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68780. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68781. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68782. }
  68783. };
  68784. FilesInput.prototype.dispose = function () {
  68785. if (!this._elementToMonitor) {
  68786. return;
  68787. }
  68788. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68789. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68790. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68791. };
  68792. FilesInput.prototype.renderFunction = function () {
  68793. if (this._additionalRenderLoopLogicCallback) {
  68794. this._additionalRenderLoopLogicCallback();
  68795. }
  68796. if (this._currentScene) {
  68797. if (this._textureLoadingCallback) {
  68798. var remaining = this._currentScene.getWaitingItemsCount();
  68799. if (remaining > 0) {
  68800. this._textureLoadingCallback(remaining);
  68801. }
  68802. }
  68803. this._currentScene.render();
  68804. }
  68805. };
  68806. FilesInput.prototype.drag = function (e) {
  68807. e.stopPropagation();
  68808. e.preventDefault();
  68809. };
  68810. FilesInput.prototype.drop = function (eventDrop) {
  68811. eventDrop.stopPropagation();
  68812. eventDrop.preventDefault();
  68813. this.loadFiles(eventDrop);
  68814. };
  68815. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68816. var _this = this;
  68817. var reader = folder.createReader();
  68818. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68819. reader.readEntries(function (entries) {
  68820. remaining.count += entries.length;
  68821. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68822. var entry = entries_1[_i];
  68823. if (entry.isFile) {
  68824. entry.file(function (file) {
  68825. file.correctName = relativePath + file.name;
  68826. files.push(file);
  68827. if (--remaining.count === 0) {
  68828. callback();
  68829. }
  68830. });
  68831. }
  68832. else if (entry.isDirectory) {
  68833. _this._traverseFolder(entry, files, remaining, callback);
  68834. }
  68835. }
  68836. if (--remaining.count) {
  68837. callback();
  68838. }
  68839. });
  68840. };
  68841. FilesInput.prototype._processFiles = function (files) {
  68842. for (var i = 0; i < files.length; i++) {
  68843. var name = files[i].correctName.toLowerCase();
  68844. var extension = name.split('.').pop();
  68845. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68846. continue;
  68847. }
  68848. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68849. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68850. this._sceneFileToLoad = files[i];
  68851. }
  68852. else {
  68853. FilesInput.FilesToLoad[name] = files[i];
  68854. }
  68855. }
  68856. };
  68857. FilesInput.prototype.loadFiles = function (event) {
  68858. var _this = this;
  68859. if (this._startingProcessingFilesCallback)
  68860. this._startingProcessingFilesCallback();
  68861. // Handling data transfer via drag'n'drop
  68862. if (event && event.dataTransfer && event.dataTransfer.files) {
  68863. this._filesToLoad = event.dataTransfer.files;
  68864. }
  68865. // Handling files from input files
  68866. if (event && event.target && event.target.files) {
  68867. this._filesToLoad = event.target.files;
  68868. }
  68869. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68870. var files_1 = new Array();
  68871. var folders = [];
  68872. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68873. for (var i = 0; i < this._filesToLoad.length; i++) {
  68874. var fileToLoad = this._filesToLoad[i];
  68875. var name_1 = fileToLoad.name.toLowerCase();
  68876. var entry = void 0;
  68877. fileToLoad.correctName = name_1;
  68878. if (items) {
  68879. var item = items[i];
  68880. if (item.getAsEntry) {
  68881. entry = item.getAsEntry();
  68882. }
  68883. else if (item.webkitGetAsEntry) {
  68884. entry = item.webkitGetAsEntry();
  68885. }
  68886. }
  68887. if (!entry) {
  68888. files_1.push(fileToLoad);
  68889. }
  68890. else {
  68891. if (entry.isDirectory) {
  68892. folders.push(entry);
  68893. }
  68894. else {
  68895. files_1.push(fileToLoad);
  68896. }
  68897. }
  68898. }
  68899. if (folders.length === 0) {
  68900. this._processFiles(files_1);
  68901. this._processReload();
  68902. }
  68903. else {
  68904. var remaining = { count: folders.length };
  68905. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68906. var folder = folders_1[_i];
  68907. this._traverseFolder(folder, files_1, remaining, function () {
  68908. _this._processFiles(files_1);
  68909. if (remaining.count === 0) {
  68910. _this._processReload();
  68911. }
  68912. });
  68913. }
  68914. }
  68915. }
  68916. };
  68917. FilesInput.prototype._processReload = function () {
  68918. if (this._onReloadCallback) {
  68919. this._onReloadCallback(this._sceneFileToLoad);
  68920. }
  68921. else {
  68922. this.reload();
  68923. }
  68924. };
  68925. FilesInput.prototype.reload = function () {
  68926. var _this = this;
  68927. // If a scene file has been provided
  68928. if (this._sceneFileToLoad) {
  68929. if (this._currentScene) {
  68930. if (BABYLON.Tools.errorsCount > 0) {
  68931. BABYLON.Tools.ClearLogCache();
  68932. }
  68933. this._engine.stopRenderLoop();
  68934. }
  68935. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68936. if (_this._progressCallback) {
  68937. _this._progressCallback(progress);
  68938. }
  68939. }).then(function (scene) {
  68940. if (_this._currentScene) {
  68941. _this._currentScene.dispose();
  68942. }
  68943. _this._currentScene = scene;
  68944. if (_this._sceneLoadedCallback) {
  68945. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68946. }
  68947. // Wait for textures and shaders to be ready
  68948. _this._currentScene.executeWhenReady(function () {
  68949. _this._engine.runRenderLoop(function () {
  68950. _this.renderFunction();
  68951. });
  68952. });
  68953. }).catch(function (error) {
  68954. if (_this._errorCallback) {
  68955. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68956. }
  68957. });
  68958. }
  68959. else {
  68960. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68961. }
  68962. };
  68963. FilesInput.FilesToLoad = {};
  68964. return FilesInput;
  68965. }());
  68966. BABYLON.FilesInput = FilesInput;
  68967. })(BABYLON || (BABYLON = {}));
  68968. //# sourceMappingURL=babylon.filesInput.js.map
  68969. var BABYLON;
  68970. (function (BABYLON) {
  68971. /**
  68972. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68973. * The underlying implementation relies on an associative array to ensure the best performances.
  68974. * The value can be anything including 'null' but except 'undefined'
  68975. */
  68976. var StringDictionary = /** @class */ (function () {
  68977. function StringDictionary() {
  68978. this._count = 0;
  68979. this._data = {};
  68980. }
  68981. /**
  68982. * This will clear this dictionary and copy the content from the 'source' one.
  68983. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68984. * @param source the dictionary to take the content from and copy to this dictionary
  68985. */
  68986. StringDictionary.prototype.copyFrom = function (source) {
  68987. var _this = this;
  68988. this.clear();
  68989. source.forEach(function (t, v) { return _this.add(t, v); });
  68990. };
  68991. /**
  68992. * Get a value based from its key
  68993. * @param key the given key to get the matching value from
  68994. * @return the value if found, otherwise undefined is returned
  68995. */
  68996. StringDictionary.prototype.get = function (key) {
  68997. var val = this._data[key];
  68998. if (val !== undefined) {
  68999. return val;
  69000. }
  69001. return undefined;
  69002. };
  69003. /**
  69004. * Get a value from its key or add it if it doesn't exist.
  69005. * This method will ensure you that a given key/data will be present in the dictionary.
  69006. * @param key the given key to get the matching value from
  69007. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69008. * The factory will only be invoked if there's no data for the given key.
  69009. * @return the value corresponding to the key.
  69010. */
  69011. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69012. var val = this.get(key);
  69013. if (val !== undefined) {
  69014. return val;
  69015. }
  69016. val = factory(key);
  69017. if (val) {
  69018. this.add(key, val);
  69019. }
  69020. return val;
  69021. };
  69022. /**
  69023. * Get a value from its key if present in the dictionary otherwise add it
  69024. * @param key the key to get the value from
  69025. * @param val if there's no such key/value pair in the dictionary add it with this value
  69026. * @return the value corresponding to the key
  69027. */
  69028. StringDictionary.prototype.getOrAdd = function (key, val) {
  69029. var curVal = this.get(key);
  69030. if (curVal !== undefined) {
  69031. return curVal;
  69032. }
  69033. this.add(key, val);
  69034. return val;
  69035. };
  69036. /**
  69037. * Check if there's a given key in the dictionary
  69038. * @param key the key to check for
  69039. * @return true if the key is present, false otherwise
  69040. */
  69041. StringDictionary.prototype.contains = function (key) {
  69042. return this._data[key] !== undefined;
  69043. };
  69044. /**
  69045. * Add a new key and its corresponding value
  69046. * @param key the key to add
  69047. * @param value the value corresponding to the key
  69048. * @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
  69049. */
  69050. StringDictionary.prototype.add = function (key, value) {
  69051. if (this._data[key] !== undefined) {
  69052. return false;
  69053. }
  69054. this._data[key] = value;
  69055. ++this._count;
  69056. return true;
  69057. };
  69058. StringDictionary.prototype.set = function (key, value) {
  69059. if (this._data[key] === undefined) {
  69060. return false;
  69061. }
  69062. this._data[key] = value;
  69063. return true;
  69064. };
  69065. /**
  69066. * Get the element of the given key and remove it from the dictionary
  69067. * @param key
  69068. */
  69069. StringDictionary.prototype.getAndRemove = function (key) {
  69070. var val = this.get(key);
  69071. if (val !== undefined) {
  69072. delete this._data[key];
  69073. --this._count;
  69074. return val;
  69075. }
  69076. return null;
  69077. };
  69078. /**
  69079. * Remove a key/value from the dictionary.
  69080. * @param key the key to remove
  69081. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69082. */
  69083. StringDictionary.prototype.remove = function (key) {
  69084. if (this.contains(key)) {
  69085. delete this._data[key];
  69086. --this._count;
  69087. return true;
  69088. }
  69089. return false;
  69090. };
  69091. /**
  69092. * Clear the whole content of the dictionary
  69093. */
  69094. StringDictionary.prototype.clear = function () {
  69095. this._data = {};
  69096. this._count = 0;
  69097. };
  69098. Object.defineProperty(StringDictionary.prototype, "count", {
  69099. get: function () {
  69100. return this._count;
  69101. },
  69102. enumerable: true,
  69103. configurable: true
  69104. });
  69105. /**
  69106. * Execute a callback on each key/val of the dictionary.
  69107. * Note that you can remove any element in this dictionary in the callback implementation
  69108. * @param callback the callback to execute on a given key/value pair
  69109. */
  69110. StringDictionary.prototype.forEach = function (callback) {
  69111. for (var cur in this._data) {
  69112. var val = this._data[cur];
  69113. callback(cur, val);
  69114. }
  69115. };
  69116. /**
  69117. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69118. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69119. * Note that you can remove any element in this dictionary in the callback implementation
  69120. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69121. */
  69122. StringDictionary.prototype.first = function (callback) {
  69123. for (var cur in this._data) {
  69124. var val = this._data[cur];
  69125. var res = callback(cur, val);
  69126. if (res) {
  69127. return res;
  69128. }
  69129. }
  69130. return null;
  69131. };
  69132. return StringDictionary;
  69133. }());
  69134. BABYLON.StringDictionary = StringDictionary;
  69135. })(BABYLON || (BABYLON = {}));
  69136. //# sourceMappingURL=babylon.stringDictionary.js.map
  69137. var BABYLON;
  69138. (function (BABYLON) {
  69139. var Tags = /** @class */ (function () {
  69140. function Tags() {
  69141. }
  69142. Tags.EnableFor = function (obj) {
  69143. obj._tags = obj._tags || {};
  69144. obj.hasTags = function () {
  69145. return Tags.HasTags(obj);
  69146. };
  69147. obj.addTags = function (tagsString) {
  69148. return Tags.AddTagsTo(obj, tagsString);
  69149. };
  69150. obj.removeTags = function (tagsString) {
  69151. return Tags.RemoveTagsFrom(obj, tagsString);
  69152. };
  69153. obj.matchesTagsQuery = function (tagsQuery) {
  69154. return Tags.MatchesQuery(obj, tagsQuery);
  69155. };
  69156. };
  69157. Tags.DisableFor = function (obj) {
  69158. delete obj._tags;
  69159. delete obj.hasTags;
  69160. delete obj.addTags;
  69161. delete obj.removeTags;
  69162. delete obj.matchesTagsQuery;
  69163. };
  69164. Tags.HasTags = function (obj) {
  69165. if (!obj._tags) {
  69166. return false;
  69167. }
  69168. return !BABYLON.Tools.IsEmpty(obj._tags);
  69169. };
  69170. Tags.GetTags = function (obj, asString) {
  69171. if (asString === void 0) { asString = true; }
  69172. if (!obj._tags) {
  69173. return null;
  69174. }
  69175. if (asString) {
  69176. var tagsArray = [];
  69177. for (var tag in obj._tags) {
  69178. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69179. tagsArray.push(tag);
  69180. }
  69181. }
  69182. return tagsArray.join(" ");
  69183. }
  69184. else {
  69185. return obj._tags;
  69186. }
  69187. };
  69188. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69189. // a tag cannot start with '||', '&&', and '!'
  69190. // it cannot contain whitespaces
  69191. Tags.AddTagsTo = function (obj, tagsString) {
  69192. if (!tagsString) {
  69193. return;
  69194. }
  69195. if (typeof tagsString !== "string") {
  69196. return;
  69197. }
  69198. var tags = tagsString.split(" ");
  69199. tags.forEach(function (tag, index, array) {
  69200. Tags._AddTagTo(obj, tag);
  69201. });
  69202. };
  69203. Tags._AddTagTo = function (obj, tag) {
  69204. tag = tag.trim();
  69205. if (tag === "" || tag === "true" || tag === "false") {
  69206. return;
  69207. }
  69208. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69209. return;
  69210. }
  69211. Tags.EnableFor(obj);
  69212. obj._tags[tag] = true;
  69213. };
  69214. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69215. if (!Tags.HasTags(obj)) {
  69216. return;
  69217. }
  69218. var tags = tagsString.split(" ");
  69219. for (var t in tags) {
  69220. Tags._RemoveTagFrom(obj, tags[t]);
  69221. }
  69222. };
  69223. Tags._RemoveTagFrom = function (obj, tag) {
  69224. delete obj._tags[tag];
  69225. };
  69226. Tags.MatchesQuery = function (obj, tagsQuery) {
  69227. if (tagsQuery === undefined) {
  69228. return true;
  69229. }
  69230. if (tagsQuery === "") {
  69231. return Tags.HasTags(obj);
  69232. }
  69233. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69234. };
  69235. return Tags;
  69236. }());
  69237. BABYLON.Tags = Tags;
  69238. })(BABYLON || (BABYLON = {}));
  69239. //# sourceMappingURL=babylon.tags.js.map
  69240. var BABYLON;
  69241. (function (BABYLON) {
  69242. /**
  69243. * Class used to evalaute queries containing `and` and `or` operators
  69244. */
  69245. var AndOrNotEvaluator = /** @class */ (function () {
  69246. function AndOrNotEvaluator() {
  69247. }
  69248. /**
  69249. * Evaluate a query
  69250. * @param query defines the query to evaluate
  69251. * @param evaluateCallback defines the callback used to filter result
  69252. * @returns true if the query matches
  69253. */
  69254. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69255. if (!query.match(/\([^\(\)]*\)/g)) {
  69256. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69257. }
  69258. else {
  69259. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69260. // remove parenthesis
  69261. r = r.slice(1, r.length - 1);
  69262. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69263. });
  69264. }
  69265. if (query === "true") {
  69266. return true;
  69267. }
  69268. if (query === "false") {
  69269. return false;
  69270. }
  69271. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69272. };
  69273. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69274. evaluateCallback = evaluateCallback || (function (r) {
  69275. return r === "true" ? true : false;
  69276. });
  69277. var result;
  69278. var or = parenthesisContent.split("||");
  69279. for (var i in or) {
  69280. if (or.hasOwnProperty(i)) {
  69281. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69282. var and = ori.split("&&");
  69283. if (and.length > 1) {
  69284. for (var j = 0; j < and.length; ++j) {
  69285. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69286. if (andj !== "true" && andj !== "false") {
  69287. if (andj[0] === "!") {
  69288. result = !evaluateCallback(andj.substring(1));
  69289. }
  69290. else {
  69291. result = evaluateCallback(andj);
  69292. }
  69293. }
  69294. else {
  69295. result = andj === "true" ? true : false;
  69296. }
  69297. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69298. ori = "false";
  69299. break;
  69300. }
  69301. }
  69302. }
  69303. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69304. result = true;
  69305. break;
  69306. }
  69307. // result equals false (or undefined)
  69308. if (ori !== "true" && ori !== "false") {
  69309. if (ori[0] === "!") {
  69310. result = !evaluateCallback(ori.substring(1));
  69311. }
  69312. else {
  69313. result = evaluateCallback(ori);
  69314. }
  69315. }
  69316. else {
  69317. result = ori === "true" ? true : false;
  69318. }
  69319. }
  69320. }
  69321. // the whole parenthesis scope is replaced by 'true' or 'false'
  69322. return result ? "true" : "false";
  69323. };
  69324. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69325. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69326. // remove whitespaces
  69327. r = r.replace(/[\s]/g, function () { return ""; });
  69328. return r.length % 2 ? "!" : "";
  69329. });
  69330. booleanString = booleanString.trim();
  69331. if (booleanString === "!true") {
  69332. booleanString = "false";
  69333. }
  69334. else if (booleanString === "!false") {
  69335. booleanString = "true";
  69336. }
  69337. return booleanString;
  69338. };
  69339. return AndOrNotEvaluator;
  69340. }());
  69341. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69342. })(BABYLON || (BABYLON = {}));
  69343. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69344. var BABYLON;
  69345. (function (BABYLON) {
  69346. /**
  69347. * Class used to enable access to IndexedDB
  69348. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69349. */
  69350. var Database = /** @class */ (function () {
  69351. /**
  69352. * Creates a new Database
  69353. * @param urlToScene defines the url to load the scene
  69354. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69355. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69356. */
  69357. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69358. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69359. var _this = this;
  69360. // Handling various flavors of prefixed version of IndexedDB
  69361. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69362. this.callbackManifestChecked = callbackManifestChecked;
  69363. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69364. this.db = null;
  69365. this._enableSceneOffline = false;
  69366. this._enableTexturesOffline = false;
  69367. this.manifestVersionFound = 0;
  69368. this.mustUpdateRessources = false;
  69369. this.hasReachedQuota = false;
  69370. if (!Database.IDBStorageEnabled) {
  69371. this.callbackManifestChecked(true);
  69372. }
  69373. else {
  69374. if (disableManifestCheck) {
  69375. this._enableSceneOffline = true;
  69376. this._enableTexturesOffline = true;
  69377. this.manifestVersionFound = 1;
  69378. BABYLON.Tools.SetImmediate(function () {
  69379. _this.callbackManifestChecked(true);
  69380. });
  69381. }
  69382. else {
  69383. this._checkManifestFile();
  69384. }
  69385. }
  69386. }
  69387. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69388. /**
  69389. * Gets a boolean indicating if scene must be saved in the database
  69390. */
  69391. get: function () {
  69392. return this._enableSceneOffline;
  69393. },
  69394. enumerable: true,
  69395. configurable: true
  69396. });
  69397. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69398. /**
  69399. * Gets a boolean indicating if textures must be saved in the database
  69400. */
  69401. get: function () {
  69402. return this._enableTexturesOffline;
  69403. },
  69404. enumerable: true,
  69405. configurable: true
  69406. });
  69407. Database.prototype._checkManifestFile = function () {
  69408. var _this = this;
  69409. var noManifestFile = function () {
  69410. _this._enableSceneOffline = false;
  69411. _this._enableTexturesOffline = false;
  69412. _this.callbackManifestChecked(false);
  69413. };
  69414. var timeStampUsed = false;
  69415. var manifestURL = this.currentSceneUrl + ".manifest";
  69416. var xhr = new XMLHttpRequest();
  69417. if (navigator.onLine) {
  69418. // Adding a timestamp to by-pass browsers' cache
  69419. timeStampUsed = true;
  69420. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69421. }
  69422. xhr.open("GET", manifestURL, true);
  69423. xhr.addEventListener("load", function () {
  69424. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69425. try {
  69426. var manifestFile = JSON.parse(xhr.response);
  69427. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69428. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69429. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69430. _this.manifestVersionFound = manifestFile.version;
  69431. }
  69432. if (_this.callbackManifestChecked) {
  69433. _this.callbackManifestChecked(true);
  69434. }
  69435. }
  69436. catch (ex) {
  69437. noManifestFile();
  69438. }
  69439. }
  69440. else {
  69441. noManifestFile();
  69442. }
  69443. }, false);
  69444. xhr.addEventListener("error", function (event) {
  69445. if (timeStampUsed) {
  69446. timeStampUsed = false;
  69447. // Let's retry without the timeStamp
  69448. // It could fail when coupled with HTML5 Offline API
  69449. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69450. xhr.open("GET", retryManifestURL, true);
  69451. xhr.send();
  69452. }
  69453. else {
  69454. noManifestFile();
  69455. }
  69456. }, false);
  69457. try {
  69458. xhr.send();
  69459. }
  69460. catch (ex) {
  69461. BABYLON.Tools.Error("Error on XHR send request.");
  69462. this.callbackManifestChecked(false);
  69463. }
  69464. };
  69465. /**
  69466. * Open the database and make it available
  69467. * @param successCallback defines the callback to call on success
  69468. * @param errorCallback defines the callback to call on error
  69469. */
  69470. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69471. var _this = this;
  69472. var handleError = function () {
  69473. _this.isSupported = false;
  69474. if (errorCallback)
  69475. errorCallback();
  69476. };
  69477. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69478. // Your browser doesn't support IndexedDB
  69479. this.isSupported = false;
  69480. if (errorCallback)
  69481. errorCallback();
  69482. }
  69483. else {
  69484. // If the DB hasn't been opened or created yet
  69485. if (!this.db) {
  69486. this.hasReachedQuota = false;
  69487. this.isSupported = true;
  69488. var request = this.idbFactory.open("babylonjs", 1);
  69489. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69490. request.onerror = function (event) {
  69491. handleError();
  69492. };
  69493. // executes when a version change transaction cannot complete due to other active transactions
  69494. request.onblocked = function (event) {
  69495. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69496. handleError();
  69497. };
  69498. // DB has been opened successfully
  69499. request.onsuccess = function (event) {
  69500. _this.db = request.result;
  69501. successCallback();
  69502. };
  69503. // Initialization of the DB. Creating Scenes & Textures stores
  69504. request.onupgradeneeded = function (event) {
  69505. _this.db = (event.target).result;
  69506. if (_this.db) {
  69507. try {
  69508. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69509. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69510. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69511. }
  69512. catch (ex) {
  69513. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69514. handleError();
  69515. }
  69516. }
  69517. };
  69518. }
  69519. // DB has already been created and opened
  69520. else {
  69521. if (successCallback)
  69522. successCallback();
  69523. }
  69524. }
  69525. };
  69526. /**
  69527. * Loads an image from the database
  69528. * @param url defines the url to load from
  69529. * @param image defines the target DOM image
  69530. */
  69531. Database.prototype.loadImageFromDB = function (url, image) {
  69532. var _this = this;
  69533. var completeURL = Database._ReturnFullUrlLocation(url);
  69534. var saveAndLoadImage = function () {
  69535. if (!_this.hasReachedQuota && _this.db !== null) {
  69536. // the texture is not yet in the DB, let's try to save it
  69537. _this._saveImageIntoDBAsync(completeURL, image);
  69538. }
  69539. // If the texture is not in the DB and we've reached the DB quota limit
  69540. // let's load it directly from the web
  69541. else {
  69542. image.src = url;
  69543. }
  69544. };
  69545. if (!this.mustUpdateRessources) {
  69546. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69547. }
  69548. // First time we're download the images or update requested in the manifest file by a version change
  69549. else {
  69550. saveAndLoadImage();
  69551. }
  69552. };
  69553. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69554. if (this.isSupported && this.db !== null) {
  69555. var texture;
  69556. var transaction = this.db.transaction(["textures"]);
  69557. transaction.onabort = function (event) {
  69558. image.src = url;
  69559. };
  69560. transaction.oncomplete = function (event) {
  69561. var blobTextureURL;
  69562. if (texture) {
  69563. var URL = window.URL || window.webkitURL;
  69564. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69565. image.onerror = function () {
  69566. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69567. image.src = url;
  69568. };
  69569. image.src = blobTextureURL;
  69570. }
  69571. else {
  69572. notInDBCallback();
  69573. }
  69574. };
  69575. var getRequest = transaction.objectStore("textures").get(url);
  69576. getRequest.onsuccess = function (event) {
  69577. texture = (event.target).result;
  69578. };
  69579. getRequest.onerror = function (event) {
  69580. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69581. image.src = url;
  69582. };
  69583. }
  69584. else {
  69585. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69586. image.src = url;
  69587. }
  69588. };
  69589. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69590. var _this = this;
  69591. if (this.isSupported) {
  69592. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69593. var generateBlobUrl = function () {
  69594. var blobTextureURL;
  69595. if (blob) {
  69596. var URL = window.URL || window.webkitURL;
  69597. try {
  69598. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69599. }
  69600. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69601. catch (ex) {
  69602. blobTextureURL = URL.createObjectURL(blob);
  69603. }
  69604. }
  69605. if (blobTextureURL) {
  69606. image.src = blobTextureURL;
  69607. }
  69608. };
  69609. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69610. var xhr = new XMLHttpRequest(), blob;
  69611. xhr.open("GET", url, true);
  69612. xhr.responseType = "blob";
  69613. xhr.addEventListener("load", function () {
  69614. if (xhr.status === 200 && _this.db) {
  69615. // Blob as response (XHR2)
  69616. blob = xhr.response;
  69617. var transaction = _this.db.transaction(["textures"], "readwrite");
  69618. // the transaction could abort because of a QuotaExceededError error
  69619. transaction.onabort = function (event) {
  69620. try {
  69621. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69622. var srcElement = (event.srcElement || event.target);
  69623. var error = srcElement.error;
  69624. if (error && error.name === "QuotaExceededError") {
  69625. _this.hasReachedQuota = true;
  69626. }
  69627. }
  69628. catch (ex) { }
  69629. generateBlobUrl();
  69630. };
  69631. transaction.oncomplete = function (event) {
  69632. generateBlobUrl();
  69633. };
  69634. var newTexture = { textureUrl: url, data: blob };
  69635. try {
  69636. // Put the blob into the dabase
  69637. var addRequest = transaction.objectStore("textures").put(newTexture);
  69638. addRequest.onsuccess = function (event) {
  69639. };
  69640. addRequest.onerror = function (event) {
  69641. generateBlobUrl();
  69642. };
  69643. }
  69644. catch (ex) {
  69645. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69646. if (ex.code === 25) {
  69647. Database.IsUASupportingBlobStorage = false;
  69648. }
  69649. image.src = url;
  69650. }
  69651. }
  69652. else {
  69653. image.src = url;
  69654. }
  69655. }, false);
  69656. xhr.addEventListener("error", function (event) {
  69657. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69658. image.src = url;
  69659. }, false);
  69660. xhr.send();
  69661. }
  69662. else {
  69663. image.src = url;
  69664. }
  69665. }
  69666. else {
  69667. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69668. image.src = url;
  69669. }
  69670. };
  69671. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69672. var _this = this;
  69673. var updateVersion = function () {
  69674. // the version is not yet in the DB or we need to update it
  69675. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69676. };
  69677. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69678. };
  69679. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69680. var _this = this;
  69681. if (this.isSupported && this.db) {
  69682. var version;
  69683. try {
  69684. var transaction = this.db.transaction(["versions"]);
  69685. transaction.oncomplete = function (event) {
  69686. if (version) {
  69687. // If the version in the JSON file is different from the version in DB
  69688. if (_this.manifestVersionFound !== version.data) {
  69689. _this.mustUpdateRessources = true;
  69690. updateInDBCallback();
  69691. }
  69692. else {
  69693. callback(version.data);
  69694. }
  69695. }
  69696. // version was not found in DB
  69697. else {
  69698. _this.mustUpdateRessources = true;
  69699. updateInDBCallback();
  69700. }
  69701. };
  69702. transaction.onabort = function (event) {
  69703. callback(-1);
  69704. };
  69705. var getRequest = transaction.objectStore("versions").get(url);
  69706. getRequest.onsuccess = function (event) {
  69707. version = (event.target).result;
  69708. };
  69709. getRequest.onerror = function (event) {
  69710. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69711. callback(-1);
  69712. };
  69713. }
  69714. catch (ex) {
  69715. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69716. callback(-1);
  69717. }
  69718. }
  69719. else {
  69720. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69721. callback(-1);
  69722. }
  69723. };
  69724. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69725. var _this = this;
  69726. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69727. try {
  69728. // Open a transaction to the database
  69729. var transaction = this.db.transaction(["versions"], "readwrite");
  69730. // the transaction could abort because of a QuotaExceededError error
  69731. transaction.onabort = function (event) {
  69732. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69733. var error = event.srcElement['error'];
  69734. if (error && error.name === "QuotaExceededError") {
  69735. _this.hasReachedQuota = true;
  69736. }
  69737. }
  69738. catch (ex) { }
  69739. callback(-1);
  69740. };
  69741. transaction.oncomplete = function (event) {
  69742. callback(_this.manifestVersionFound);
  69743. };
  69744. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69745. // Put the scene into the database
  69746. var addRequest = transaction.objectStore("versions").put(newVersion);
  69747. addRequest.onsuccess = function (event) {
  69748. };
  69749. addRequest.onerror = function (event) {
  69750. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69751. };
  69752. }
  69753. catch (ex) {
  69754. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69755. callback(-1);
  69756. }
  69757. }
  69758. else {
  69759. callback(-1);
  69760. }
  69761. };
  69762. /**
  69763. * Loads a file from database
  69764. * @param url defines the URL to load from
  69765. * @param sceneLoaded defines a callback to call on success
  69766. * @param progressCallBack defines a callback to call when progress changed
  69767. * @param errorCallback defines a callback to call on error
  69768. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69769. */
  69770. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69771. var _this = this;
  69772. var completeUrl = Database._ReturnFullUrlLocation(url);
  69773. var saveAndLoadFile = function () {
  69774. // the scene is not yet in the DB, let's try to save it
  69775. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69776. };
  69777. this._checkVersionFromDB(completeUrl, function (version) {
  69778. if (version !== -1) {
  69779. if (!_this.mustUpdateRessources) {
  69780. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69781. }
  69782. else {
  69783. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69784. }
  69785. }
  69786. else {
  69787. if (errorCallback) {
  69788. errorCallback();
  69789. }
  69790. }
  69791. });
  69792. };
  69793. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69794. if (this.isSupported && this.db) {
  69795. var targetStore;
  69796. if (url.indexOf(".babylon") !== -1) {
  69797. targetStore = "scenes";
  69798. }
  69799. else {
  69800. targetStore = "textures";
  69801. }
  69802. var file;
  69803. var transaction = this.db.transaction([targetStore]);
  69804. transaction.oncomplete = function (event) {
  69805. if (file) {
  69806. callback(file.data);
  69807. }
  69808. // file was not found in DB
  69809. else {
  69810. notInDBCallback();
  69811. }
  69812. };
  69813. transaction.onabort = function (event) {
  69814. notInDBCallback();
  69815. };
  69816. var getRequest = transaction.objectStore(targetStore).get(url);
  69817. getRequest.onsuccess = function (event) {
  69818. file = (event.target).result;
  69819. };
  69820. getRequest.onerror = function (event) {
  69821. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69822. notInDBCallback();
  69823. };
  69824. }
  69825. else {
  69826. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69827. callback();
  69828. }
  69829. };
  69830. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69831. var _this = this;
  69832. if (this.isSupported) {
  69833. var targetStore;
  69834. if (url.indexOf(".babylon") !== -1) {
  69835. targetStore = "scenes";
  69836. }
  69837. else {
  69838. targetStore = "textures";
  69839. }
  69840. // Create XHR
  69841. var xhr = new XMLHttpRequest();
  69842. var fileData;
  69843. xhr.open("GET", url, true);
  69844. if (useArrayBuffer) {
  69845. xhr.responseType = "arraybuffer";
  69846. }
  69847. if (progressCallback) {
  69848. xhr.onprogress = progressCallback;
  69849. }
  69850. xhr.addEventListener("load", function () {
  69851. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69852. // Blob as response (XHR2)
  69853. //fileData = xhr.responseText;
  69854. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69855. if (!_this.hasReachedQuota && _this.db) {
  69856. // Open a transaction to the database
  69857. var transaction = _this.db.transaction([targetStore], "readwrite");
  69858. // the transaction could abort because of a QuotaExceededError error
  69859. transaction.onabort = function (event) {
  69860. try {
  69861. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69862. var error = event.srcElement['error'];
  69863. if (error && error.name === "QuotaExceededError") {
  69864. _this.hasReachedQuota = true;
  69865. }
  69866. }
  69867. catch (ex) { }
  69868. callback(fileData);
  69869. };
  69870. transaction.oncomplete = function (event) {
  69871. callback(fileData);
  69872. };
  69873. var newFile;
  69874. if (targetStore === "scenes") {
  69875. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69876. }
  69877. else {
  69878. newFile = { textureUrl: url, data: fileData };
  69879. }
  69880. try {
  69881. // Put the scene into the database
  69882. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69883. addRequest.onsuccess = function (event) {
  69884. };
  69885. addRequest.onerror = function (event) {
  69886. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69887. };
  69888. }
  69889. catch (ex) {
  69890. callback(fileData);
  69891. }
  69892. }
  69893. else {
  69894. callback(fileData);
  69895. }
  69896. }
  69897. else {
  69898. callback();
  69899. }
  69900. }, false);
  69901. xhr.addEventListener("error", function (event) {
  69902. BABYLON.Tools.Error("error on XHR request.");
  69903. callback();
  69904. }, false);
  69905. xhr.send();
  69906. }
  69907. else {
  69908. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69909. callback();
  69910. }
  69911. };
  69912. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69913. Database.IsUASupportingBlobStorage = true;
  69914. /** Gets a boolean indicating if Database storate is enabled */
  69915. Database.IDBStorageEnabled = true;
  69916. Database._ParseURL = function (url) {
  69917. var a = document.createElement('a');
  69918. a.href = url;
  69919. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69920. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69921. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69922. return absLocation;
  69923. };
  69924. Database._ReturnFullUrlLocation = function (url) {
  69925. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69926. return (Database._ParseURL(window.location.href) + url);
  69927. }
  69928. else {
  69929. return url;
  69930. }
  69931. };
  69932. return Database;
  69933. }());
  69934. BABYLON.Database = Database;
  69935. })(BABYLON || (BABYLON = {}));
  69936. //# sourceMappingURL=babylon.database.js.map
  69937. var BABYLON;
  69938. (function (BABYLON) {
  69939. var FresnelParameters = /** @class */ (function () {
  69940. function FresnelParameters() {
  69941. this._isEnabled = true;
  69942. this.leftColor = BABYLON.Color3.White();
  69943. this.rightColor = BABYLON.Color3.Black();
  69944. this.bias = 0;
  69945. this.power = 1;
  69946. }
  69947. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69948. get: function () {
  69949. return this._isEnabled;
  69950. },
  69951. set: function (value) {
  69952. if (this._isEnabled === value) {
  69953. return;
  69954. }
  69955. this._isEnabled = value;
  69956. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69957. },
  69958. enumerable: true,
  69959. configurable: true
  69960. });
  69961. FresnelParameters.prototype.clone = function () {
  69962. var newFresnelParameters = new FresnelParameters();
  69963. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69964. return newFresnelParameters;
  69965. };
  69966. FresnelParameters.prototype.serialize = function () {
  69967. var serializationObject = {};
  69968. serializationObject.isEnabled = this.isEnabled;
  69969. serializationObject.leftColor = this.leftColor.asArray();
  69970. serializationObject.rightColor = this.rightColor.asArray();
  69971. serializationObject.bias = this.bias;
  69972. serializationObject.power = this.power;
  69973. return serializationObject;
  69974. };
  69975. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69976. var fresnelParameters = new FresnelParameters();
  69977. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69978. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69979. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69980. fresnelParameters.bias = parsedFresnelParameters.bias;
  69981. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69982. return fresnelParameters;
  69983. };
  69984. return FresnelParameters;
  69985. }());
  69986. BABYLON.FresnelParameters = FresnelParameters;
  69987. })(BABYLON || (BABYLON = {}));
  69988. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69989. var BABYLON;
  69990. (function (BABYLON) {
  69991. var MultiMaterial = /** @class */ (function (_super) {
  69992. __extends(MultiMaterial, _super);
  69993. function MultiMaterial(name, scene) {
  69994. var _this = _super.call(this, name, scene, true) || this;
  69995. scene.multiMaterials.push(_this);
  69996. _this.subMaterials = new Array();
  69997. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69998. return _this;
  69999. }
  70000. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70001. get: function () {
  70002. return this._subMaterials;
  70003. },
  70004. set: function (value) {
  70005. this._subMaterials = value;
  70006. this._hookArray(value);
  70007. },
  70008. enumerable: true,
  70009. configurable: true
  70010. });
  70011. MultiMaterial.prototype._hookArray = function (array) {
  70012. var _this = this;
  70013. var oldPush = array.push;
  70014. array.push = function () {
  70015. var items = [];
  70016. for (var _i = 0; _i < arguments.length; _i++) {
  70017. items[_i] = arguments[_i];
  70018. }
  70019. var result = oldPush.apply(array, items);
  70020. _this._markAllSubMeshesAsTexturesDirty();
  70021. return result;
  70022. };
  70023. var oldSplice = array.splice;
  70024. array.splice = function (index, deleteCount) {
  70025. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70026. _this._markAllSubMeshesAsTexturesDirty();
  70027. return deleted;
  70028. };
  70029. };
  70030. // Properties
  70031. MultiMaterial.prototype.getSubMaterial = function (index) {
  70032. if (index < 0 || index >= this.subMaterials.length) {
  70033. return this.getScene().defaultMaterial;
  70034. }
  70035. return this.subMaterials[index];
  70036. };
  70037. MultiMaterial.prototype.getActiveTextures = function () {
  70038. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70039. if (subMaterial) {
  70040. return subMaterial.getActiveTextures();
  70041. }
  70042. else {
  70043. return [];
  70044. }
  70045. }));
  70046. var _a;
  70047. };
  70048. // Methods
  70049. MultiMaterial.prototype.getClassName = function () {
  70050. return "MultiMaterial";
  70051. };
  70052. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70053. for (var index = 0; index < this.subMaterials.length; index++) {
  70054. var subMaterial = this.subMaterials[index];
  70055. if (subMaterial) {
  70056. if (subMaterial.storeEffectOnSubMeshes) {
  70057. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70058. return false;
  70059. }
  70060. continue;
  70061. }
  70062. if (!subMaterial.isReady(mesh)) {
  70063. return false;
  70064. }
  70065. }
  70066. }
  70067. return true;
  70068. };
  70069. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70070. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70071. for (var index = 0; index < this.subMaterials.length; index++) {
  70072. var subMaterial = null;
  70073. var current = this.subMaterials[index];
  70074. if (cloneChildren && current) {
  70075. subMaterial = current.clone(name + "-" + current.name);
  70076. }
  70077. else {
  70078. subMaterial = this.subMaterials[index];
  70079. }
  70080. newMultiMaterial.subMaterials.push(subMaterial);
  70081. }
  70082. return newMultiMaterial;
  70083. };
  70084. MultiMaterial.prototype.serialize = function () {
  70085. var serializationObject = {};
  70086. serializationObject.name = this.name;
  70087. serializationObject.id = this.id;
  70088. if (BABYLON.Tags) {
  70089. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70090. }
  70091. serializationObject.materials = [];
  70092. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70093. var subMat = this.subMaterials[matIndex];
  70094. if (subMat) {
  70095. serializationObject.materials.push(subMat.id);
  70096. }
  70097. else {
  70098. serializationObject.materials.push(null);
  70099. }
  70100. }
  70101. return serializationObject;
  70102. };
  70103. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70104. var scene = this.getScene();
  70105. if (!scene) {
  70106. return;
  70107. }
  70108. var index = scene.multiMaterials.indexOf(this);
  70109. if (index >= 0) {
  70110. scene.multiMaterials.splice(index, 1);
  70111. }
  70112. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70113. };
  70114. return MultiMaterial;
  70115. }(BABYLON.Material));
  70116. BABYLON.MultiMaterial = MultiMaterial;
  70117. })(BABYLON || (BABYLON = {}));
  70118. //# sourceMappingURL=babylon.multiMaterial.js.map
  70119. var BABYLON;
  70120. (function (BABYLON) {
  70121. var FreeCameraTouchInput = /** @class */ (function () {
  70122. function FreeCameraTouchInput() {
  70123. this._offsetX = null;
  70124. this._offsetY = null;
  70125. this._pointerPressed = new Array();
  70126. this.touchAngularSensibility = 200000.0;
  70127. this.touchMoveSensibility = 250.0;
  70128. }
  70129. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70130. var _this = this;
  70131. var previousPosition = null;
  70132. if (this._pointerInput === undefined) {
  70133. this._onLostFocus = function (evt) {
  70134. _this._offsetX = null;
  70135. _this._offsetY = null;
  70136. };
  70137. this._pointerInput = function (p, s) {
  70138. var evt = p.event;
  70139. if (evt.pointerType === "mouse") {
  70140. return;
  70141. }
  70142. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70143. if (!noPreventDefault) {
  70144. evt.preventDefault();
  70145. }
  70146. _this._pointerPressed.push(evt.pointerId);
  70147. if (_this._pointerPressed.length !== 1) {
  70148. return;
  70149. }
  70150. previousPosition = {
  70151. x: evt.clientX,
  70152. y: evt.clientY
  70153. };
  70154. }
  70155. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70156. if (!noPreventDefault) {
  70157. evt.preventDefault();
  70158. }
  70159. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70160. if (index === -1) {
  70161. return;
  70162. }
  70163. _this._pointerPressed.splice(index, 1);
  70164. if (index != 0) {
  70165. return;
  70166. }
  70167. previousPosition = null;
  70168. _this._offsetX = null;
  70169. _this._offsetY = null;
  70170. }
  70171. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70172. if (!noPreventDefault) {
  70173. evt.preventDefault();
  70174. }
  70175. if (!previousPosition) {
  70176. return;
  70177. }
  70178. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70179. if (index != 0) {
  70180. return;
  70181. }
  70182. _this._offsetX = evt.clientX - previousPosition.x;
  70183. _this._offsetY = -(evt.clientY - previousPosition.y);
  70184. }
  70185. };
  70186. }
  70187. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70188. if (this._onLostFocus) {
  70189. element.addEventListener("blur", this._onLostFocus);
  70190. }
  70191. };
  70192. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70193. if (this._pointerInput && element) {
  70194. if (this._observer) {
  70195. this.camera.getScene().onPointerObservable.remove(this._observer);
  70196. this._observer = null;
  70197. }
  70198. if (this._onLostFocus) {
  70199. element.removeEventListener("blur", this._onLostFocus);
  70200. this._onLostFocus = null;
  70201. }
  70202. this._pointerPressed = [];
  70203. this._offsetX = null;
  70204. this._offsetY = null;
  70205. }
  70206. };
  70207. FreeCameraTouchInput.prototype.checkInputs = function () {
  70208. if (this._offsetX && this._offsetY) {
  70209. var camera = this.camera;
  70210. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70211. if (this._pointerPressed.length > 1) {
  70212. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70213. }
  70214. else {
  70215. var speed = camera._computeLocalCameraSpeed();
  70216. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70217. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70218. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70219. }
  70220. }
  70221. };
  70222. FreeCameraTouchInput.prototype.getClassName = function () {
  70223. return "FreeCameraTouchInput";
  70224. };
  70225. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70226. return "touch";
  70227. };
  70228. __decorate([
  70229. BABYLON.serialize()
  70230. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70231. __decorate([
  70232. BABYLON.serialize()
  70233. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70234. return FreeCameraTouchInput;
  70235. }());
  70236. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70237. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70238. })(BABYLON || (BABYLON = {}));
  70239. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70240. var BABYLON;
  70241. (function (BABYLON) {
  70242. // We're mainly based on the logic defined into the FreeCamera code
  70243. var TouchCamera = /** @class */ (function (_super) {
  70244. __extends(TouchCamera, _super);
  70245. //-- end properties for backward compatibility for inputs
  70246. function TouchCamera(name, position, scene) {
  70247. var _this = _super.call(this, name, position, scene) || this;
  70248. _this.inputs.addTouch();
  70249. _this._setupInputs();
  70250. return _this;
  70251. }
  70252. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70253. //-- Begin properties for backward compatibility for inputs
  70254. get: function () {
  70255. var touch = this.inputs.attached["touch"];
  70256. if (touch)
  70257. return touch.touchAngularSensibility;
  70258. return 0;
  70259. },
  70260. set: function (value) {
  70261. var touch = this.inputs.attached["touch"];
  70262. if (touch)
  70263. touch.touchAngularSensibility = value;
  70264. },
  70265. enumerable: true,
  70266. configurable: true
  70267. });
  70268. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70269. get: function () {
  70270. var touch = this.inputs.attached["touch"];
  70271. if (touch)
  70272. return touch.touchMoveSensibility;
  70273. return 0;
  70274. },
  70275. set: function (value) {
  70276. var touch = this.inputs.attached["touch"];
  70277. if (touch)
  70278. touch.touchMoveSensibility = value;
  70279. },
  70280. enumerable: true,
  70281. configurable: true
  70282. });
  70283. TouchCamera.prototype.getClassName = function () {
  70284. return "TouchCamera";
  70285. };
  70286. TouchCamera.prototype._setupInputs = function () {
  70287. var mouse = this.inputs.attached["mouse"];
  70288. if (mouse) {
  70289. mouse.touchEnabled = false;
  70290. }
  70291. };
  70292. return TouchCamera;
  70293. }(BABYLON.FreeCamera));
  70294. BABYLON.TouchCamera = TouchCamera;
  70295. })(BABYLON || (BABYLON = {}));
  70296. //# sourceMappingURL=babylon.touchCamera.js.map
  70297. var BABYLON;
  70298. (function (BABYLON) {
  70299. var ProceduralTexture = /** @class */ (function (_super) {
  70300. __extends(ProceduralTexture, _super);
  70301. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70302. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70303. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70304. if (isCube === void 0) { isCube = false; }
  70305. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70306. _this.isCube = isCube;
  70307. _this.isEnabled = true;
  70308. _this._currentRefreshId = -1;
  70309. _this._refreshRate = 1;
  70310. _this._vertexBuffers = {};
  70311. _this._uniforms = new Array();
  70312. _this._samplers = new Array();
  70313. _this._textures = {};
  70314. _this._floats = {};
  70315. _this._floatsArrays = {};
  70316. _this._colors3 = {};
  70317. _this._colors4 = {};
  70318. _this._vectors2 = {};
  70319. _this._vectors3 = {};
  70320. _this._matrices = {};
  70321. _this._fallbackTextureUsed = false;
  70322. scene.proceduralTextures.push(_this);
  70323. _this._engine = scene.getEngine();
  70324. _this.name = name;
  70325. _this.isRenderTarget = true;
  70326. _this._size = size;
  70327. _this._generateMipMaps = generateMipMaps;
  70328. _this.setFragment(fragment);
  70329. _this._fallbackTexture = fallbackTexture;
  70330. if (isCube) {
  70331. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70332. _this.setFloat("face", 0);
  70333. }
  70334. else {
  70335. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70336. }
  70337. // VBO
  70338. var vertices = [];
  70339. vertices.push(1, 1);
  70340. vertices.push(-1, 1);
  70341. vertices.push(-1, -1);
  70342. vertices.push(1, -1);
  70343. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70344. _this._createIndexBuffer();
  70345. return _this;
  70346. }
  70347. ProceduralTexture.prototype._createIndexBuffer = function () {
  70348. var engine = this._engine;
  70349. // Indices
  70350. var indices = [];
  70351. indices.push(0);
  70352. indices.push(1);
  70353. indices.push(2);
  70354. indices.push(0);
  70355. indices.push(2);
  70356. indices.push(3);
  70357. this._indexBuffer = engine.createIndexBuffer(indices);
  70358. };
  70359. ProceduralTexture.prototype._rebuild = function () {
  70360. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70361. if (vb) {
  70362. vb._rebuild();
  70363. }
  70364. this._createIndexBuffer();
  70365. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70366. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70367. }
  70368. };
  70369. ProceduralTexture.prototype.reset = function () {
  70370. if (this._effect === undefined) {
  70371. return;
  70372. }
  70373. var engine = this._engine;
  70374. engine._releaseEffect(this._effect);
  70375. };
  70376. ProceduralTexture.prototype.isReady = function () {
  70377. var _this = this;
  70378. var engine = this._engine;
  70379. var shaders;
  70380. if (!this._fragment) {
  70381. return false;
  70382. }
  70383. if (this._fallbackTextureUsed) {
  70384. return true;
  70385. }
  70386. if (this._fragment.fragmentElement !== undefined) {
  70387. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70388. }
  70389. else {
  70390. shaders = { vertex: "procedural", fragment: this._fragment };
  70391. }
  70392. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70393. _this.releaseInternalTexture();
  70394. if (_this._fallbackTexture) {
  70395. _this._texture = _this._fallbackTexture._texture;
  70396. if (_this._texture) {
  70397. _this._texture.incrementReferences();
  70398. }
  70399. }
  70400. _this._fallbackTextureUsed = true;
  70401. });
  70402. return this._effect.isReady();
  70403. };
  70404. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70405. this._currentRefreshId = -1;
  70406. };
  70407. ProceduralTexture.prototype.setFragment = function (fragment) {
  70408. this._fragment = fragment;
  70409. };
  70410. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70411. get: function () {
  70412. return this._refreshRate;
  70413. },
  70414. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70415. set: function (value) {
  70416. this._refreshRate = value;
  70417. this.resetRefreshCounter();
  70418. },
  70419. enumerable: true,
  70420. configurable: true
  70421. });
  70422. ProceduralTexture.prototype._shouldRender = function () {
  70423. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70424. return false;
  70425. }
  70426. if (this._fallbackTextureUsed) {
  70427. return false;
  70428. }
  70429. if (this._currentRefreshId === -1) { // At least render once
  70430. this._currentRefreshId = 1;
  70431. return true;
  70432. }
  70433. if (this.refreshRate === this._currentRefreshId) {
  70434. this._currentRefreshId = 1;
  70435. return true;
  70436. }
  70437. this._currentRefreshId++;
  70438. return false;
  70439. };
  70440. ProceduralTexture.prototype.getRenderSize = function () {
  70441. return this._size;
  70442. };
  70443. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70444. if (this._fallbackTextureUsed) {
  70445. return;
  70446. }
  70447. this.releaseInternalTexture();
  70448. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70449. };
  70450. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70451. if (this._uniforms.indexOf(uniformName) === -1) {
  70452. this._uniforms.push(uniformName);
  70453. }
  70454. };
  70455. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70456. if (this._samplers.indexOf(name) === -1) {
  70457. this._samplers.push(name);
  70458. }
  70459. this._textures[name] = texture;
  70460. return this;
  70461. };
  70462. ProceduralTexture.prototype.setFloat = function (name, value) {
  70463. this._checkUniform(name);
  70464. this._floats[name] = value;
  70465. return this;
  70466. };
  70467. ProceduralTexture.prototype.setFloats = function (name, value) {
  70468. this._checkUniform(name);
  70469. this._floatsArrays[name] = value;
  70470. return this;
  70471. };
  70472. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70473. this._checkUniform(name);
  70474. this._colors3[name] = value;
  70475. return this;
  70476. };
  70477. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70478. this._checkUniform(name);
  70479. this._colors4[name] = value;
  70480. return this;
  70481. };
  70482. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70483. this._checkUniform(name);
  70484. this._vectors2[name] = value;
  70485. return this;
  70486. };
  70487. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70488. this._checkUniform(name);
  70489. this._vectors3[name] = value;
  70490. return this;
  70491. };
  70492. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70493. this._checkUniform(name);
  70494. this._matrices[name] = value;
  70495. return this;
  70496. };
  70497. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70498. var scene = this.getScene();
  70499. if (!scene) {
  70500. return;
  70501. }
  70502. var engine = this._engine;
  70503. // Render
  70504. engine.enableEffect(this._effect);
  70505. engine.setState(false);
  70506. // Texture
  70507. for (var name in this._textures) {
  70508. this._effect.setTexture(name, this._textures[name]);
  70509. }
  70510. // Float
  70511. for (name in this._floats) {
  70512. this._effect.setFloat(name, this._floats[name]);
  70513. }
  70514. // Floats
  70515. for (name in this._floatsArrays) {
  70516. this._effect.setArray(name, this._floatsArrays[name]);
  70517. }
  70518. // Color3
  70519. for (name in this._colors3) {
  70520. this._effect.setColor3(name, this._colors3[name]);
  70521. }
  70522. // Color4
  70523. for (name in this._colors4) {
  70524. var color = this._colors4[name];
  70525. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70526. }
  70527. // Vector2
  70528. for (name in this._vectors2) {
  70529. this._effect.setVector2(name, this._vectors2[name]);
  70530. }
  70531. // Vector3
  70532. for (name in this._vectors3) {
  70533. this._effect.setVector3(name, this._vectors3[name]);
  70534. }
  70535. // Matrix
  70536. for (name in this._matrices) {
  70537. this._effect.setMatrix(name, this._matrices[name]);
  70538. }
  70539. if (!this._texture) {
  70540. return;
  70541. }
  70542. if (this.isCube) {
  70543. for (var face = 0; face < 6; face++) {
  70544. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70545. // VBOs
  70546. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70547. this._effect.setFloat("face", face);
  70548. // Clear
  70549. engine.clear(scene.clearColor, true, true, true);
  70550. // Draw order
  70551. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70552. // Mipmaps
  70553. if (face === 5) {
  70554. engine.generateMipMapsForCubemap(this._texture);
  70555. }
  70556. }
  70557. }
  70558. else {
  70559. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70560. // VBOs
  70561. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70562. // Clear
  70563. engine.clear(scene.clearColor, true, true, true);
  70564. // Draw order
  70565. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70566. }
  70567. // Unbind
  70568. engine.unBindFramebuffer(this._texture, this.isCube);
  70569. if (this.onGenerated) {
  70570. this.onGenerated();
  70571. }
  70572. };
  70573. ProceduralTexture.prototype.clone = function () {
  70574. var textureSize = this.getSize();
  70575. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70576. // Base texture
  70577. newTexture.hasAlpha = this.hasAlpha;
  70578. newTexture.level = this.level;
  70579. // RenderTarget Texture
  70580. newTexture.coordinatesMode = this.coordinatesMode;
  70581. return newTexture;
  70582. };
  70583. ProceduralTexture.prototype.dispose = function () {
  70584. var scene = this.getScene();
  70585. if (!scene) {
  70586. return;
  70587. }
  70588. var index = scene.proceduralTextures.indexOf(this);
  70589. if (index >= 0) {
  70590. scene.proceduralTextures.splice(index, 1);
  70591. }
  70592. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70593. if (vertexBuffer) {
  70594. vertexBuffer.dispose();
  70595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70596. }
  70597. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70598. this._indexBuffer = null;
  70599. }
  70600. _super.prototype.dispose.call(this);
  70601. };
  70602. return ProceduralTexture;
  70603. }(BABYLON.Texture));
  70604. BABYLON.ProceduralTexture = ProceduralTexture;
  70605. })(BABYLON || (BABYLON = {}));
  70606. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70607. var BABYLON;
  70608. (function (BABYLON) {
  70609. var CustomProceduralTexture = /** @class */ (function (_super) {
  70610. __extends(CustomProceduralTexture, _super);
  70611. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70612. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70613. _this._animate = true;
  70614. _this._time = 0;
  70615. _this._texturePath = texturePath;
  70616. //Try to load json
  70617. _this.loadJson(texturePath);
  70618. _this.refreshRate = 1;
  70619. return _this;
  70620. }
  70621. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70622. var _this = this;
  70623. var noConfigFile = function () {
  70624. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70625. try {
  70626. _this.setFragment(_this._texturePath);
  70627. }
  70628. catch (ex) {
  70629. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70630. }
  70631. };
  70632. var configFileUrl = jsonUrl + "/config.json";
  70633. var xhr = new XMLHttpRequest();
  70634. xhr.open("GET", configFileUrl, true);
  70635. xhr.addEventListener("load", function () {
  70636. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70637. try {
  70638. _this._config = JSON.parse(xhr.response);
  70639. _this.updateShaderUniforms();
  70640. _this.updateTextures();
  70641. _this.setFragment(_this._texturePath + "/custom");
  70642. _this._animate = _this._config.animate;
  70643. _this.refreshRate = _this._config.refreshrate;
  70644. }
  70645. catch (ex) {
  70646. noConfigFile();
  70647. }
  70648. }
  70649. else {
  70650. noConfigFile();
  70651. }
  70652. }, false);
  70653. xhr.addEventListener("error", function () {
  70654. noConfigFile();
  70655. }, false);
  70656. try {
  70657. xhr.send();
  70658. }
  70659. catch (ex) {
  70660. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70661. }
  70662. };
  70663. CustomProceduralTexture.prototype.isReady = function () {
  70664. if (!_super.prototype.isReady.call(this)) {
  70665. return false;
  70666. }
  70667. for (var name in this._textures) {
  70668. var texture = this._textures[name];
  70669. if (!texture.isReady()) {
  70670. return false;
  70671. }
  70672. }
  70673. return true;
  70674. };
  70675. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70676. var scene = this.getScene();
  70677. if (this._animate && scene) {
  70678. this._time += scene.getAnimationRatio() * 0.03;
  70679. this.updateShaderUniforms();
  70680. }
  70681. _super.prototype.render.call(this, useCameraPostProcess);
  70682. };
  70683. CustomProceduralTexture.prototype.updateTextures = function () {
  70684. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70685. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70686. }
  70687. };
  70688. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70689. if (this._config) {
  70690. for (var j = 0; j < this._config.uniforms.length; j++) {
  70691. var uniform = this._config.uniforms[j];
  70692. switch (uniform.type) {
  70693. case "float":
  70694. this.setFloat(uniform.name, uniform.value);
  70695. break;
  70696. case "color3":
  70697. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70698. break;
  70699. case "color4":
  70700. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70701. break;
  70702. case "vector2":
  70703. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70704. break;
  70705. case "vector3":
  70706. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70707. break;
  70708. }
  70709. }
  70710. }
  70711. this.setFloat("time", this._time);
  70712. };
  70713. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70714. get: function () {
  70715. return this._animate;
  70716. },
  70717. set: function (value) {
  70718. this._animate = value;
  70719. },
  70720. enumerable: true,
  70721. configurable: true
  70722. });
  70723. return CustomProceduralTexture;
  70724. }(BABYLON.ProceduralTexture));
  70725. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70726. })(BABYLON || (BABYLON = {}));
  70727. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70728. var BABYLON;
  70729. (function (BABYLON) {
  70730. var FreeCameraGamepadInput = /** @class */ (function () {
  70731. function FreeCameraGamepadInput() {
  70732. this.gamepadAngularSensibility = 200;
  70733. this.gamepadMoveSensibility = 40;
  70734. // private members
  70735. this._cameraTransform = BABYLON.Matrix.Identity();
  70736. this._deltaTransform = BABYLON.Vector3.Zero();
  70737. this._vector3 = BABYLON.Vector3.Zero();
  70738. this._vector2 = BABYLON.Vector2.Zero();
  70739. }
  70740. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70741. var _this = this;
  70742. var manager = this.camera.getScene().gamepadManager;
  70743. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70744. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70745. // prioritize XBOX gamepads.
  70746. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70747. _this.gamepad = gamepad;
  70748. }
  70749. }
  70750. });
  70751. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70752. if (_this.gamepad === gamepad) {
  70753. _this.gamepad = null;
  70754. }
  70755. });
  70756. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70757. };
  70758. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70759. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70760. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70761. this.gamepad = null;
  70762. };
  70763. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70764. if (this.gamepad && this.gamepad.leftStick) {
  70765. var camera = this.camera;
  70766. var LSValues = this.gamepad.leftStick;
  70767. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70768. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70769. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70770. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70771. var RSValues = this.gamepad.rightStick;
  70772. if (RSValues) {
  70773. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70774. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70775. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70776. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70777. }
  70778. else {
  70779. RSValues = { x: 0, y: 0 };
  70780. }
  70781. if (!camera.rotationQuaternion) {
  70782. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70783. }
  70784. else {
  70785. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70786. }
  70787. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70788. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70789. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70790. camera.cameraDirection.addInPlace(this._deltaTransform);
  70791. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70792. camera.cameraRotation.addInPlace(this._vector2);
  70793. }
  70794. };
  70795. FreeCameraGamepadInput.prototype.getClassName = function () {
  70796. return "FreeCameraGamepadInput";
  70797. };
  70798. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70799. return "gamepad";
  70800. };
  70801. __decorate([
  70802. BABYLON.serialize()
  70803. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70804. __decorate([
  70805. BABYLON.serialize()
  70806. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70807. return FreeCameraGamepadInput;
  70808. }());
  70809. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70810. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70811. })(BABYLON || (BABYLON = {}));
  70812. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70813. var BABYLON;
  70814. (function (BABYLON) {
  70815. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70816. function ArcRotateCameraGamepadInput() {
  70817. this.gamepadRotationSensibility = 80;
  70818. this.gamepadMoveSensibility = 40;
  70819. }
  70820. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70821. var _this = this;
  70822. var manager = this.camera.getScene().gamepadManager;
  70823. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70824. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70825. // prioritize XBOX gamepads.
  70826. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70827. _this.gamepad = gamepad;
  70828. }
  70829. }
  70830. });
  70831. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70832. if (_this.gamepad === gamepad) {
  70833. _this.gamepad = null;
  70834. }
  70835. });
  70836. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70837. };
  70838. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70839. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70840. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70841. this.gamepad = null;
  70842. };
  70843. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70844. if (this.gamepad) {
  70845. var camera = this.camera;
  70846. var RSValues = this.gamepad.rightStick;
  70847. if (RSValues) {
  70848. if (RSValues.x != 0) {
  70849. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70850. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70851. camera.inertialAlphaOffset += normalizedRX;
  70852. }
  70853. }
  70854. if (RSValues.y != 0) {
  70855. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70856. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70857. camera.inertialBetaOffset += normalizedRY;
  70858. }
  70859. }
  70860. }
  70861. var LSValues = this.gamepad.leftStick;
  70862. if (LSValues && LSValues.y != 0) {
  70863. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70864. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70865. this.camera.inertialRadiusOffset -= normalizedLY;
  70866. }
  70867. }
  70868. }
  70869. };
  70870. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70871. return "ArcRotateCameraGamepadInput";
  70872. };
  70873. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70874. return "gamepad";
  70875. };
  70876. __decorate([
  70877. BABYLON.serialize()
  70878. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70879. __decorate([
  70880. BABYLON.serialize()
  70881. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70882. return ArcRotateCameraGamepadInput;
  70883. }());
  70884. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70885. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70886. })(BABYLON || (BABYLON = {}));
  70887. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70888. var BABYLON;
  70889. (function (BABYLON) {
  70890. var GamepadManager = /** @class */ (function () {
  70891. function GamepadManager(_scene) {
  70892. var _this = this;
  70893. this._scene = _scene;
  70894. this._babylonGamepads = [];
  70895. this._oneGamepadConnected = false;
  70896. this._isMonitoring = false;
  70897. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70898. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70899. this._gamepadEventSupported = false;
  70900. }
  70901. else {
  70902. this._gamepadEventSupported = 'GamepadEvent' in window;
  70903. this._gamepadSupport = (navigator.getGamepads ||
  70904. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70905. }
  70906. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70907. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70908. for (var i in _this._babylonGamepads) {
  70909. var gamepad = _this._babylonGamepads[i];
  70910. if (gamepad && gamepad._isConnected) {
  70911. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70912. }
  70913. }
  70914. });
  70915. this._onGamepadConnectedEvent = function (evt) {
  70916. var gamepad = evt.gamepad;
  70917. if (gamepad.index in _this._babylonGamepads) {
  70918. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70919. return;
  70920. }
  70921. }
  70922. var newGamepad;
  70923. if (_this._babylonGamepads[gamepad.index]) {
  70924. newGamepad = _this._babylonGamepads[gamepad.index];
  70925. newGamepad.browserGamepad = gamepad;
  70926. newGamepad._isConnected = true;
  70927. }
  70928. else {
  70929. newGamepad = _this._addNewGamepad(gamepad);
  70930. }
  70931. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70932. _this._startMonitoringGamepads();
  70933. };
  70934. this._onGamepadDisconnectedEvent = function (evt) {
  70935. var gamepad = evt.gamepad;
  70936. // Remove the gamepad from the list of gamepads to monitor.
  70937. for (var i in _this._babylonGamepads) {
  70938. if (_this._babylonGamepads[i].index === gamepad.index) {
  70939. var disconnectedGamepad = _this._babylonGamepads[i];
  70940. disconnectedGamepad._isConnected = false;
  70941. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70942. break;
  70943. }
  70944. }
  70945. };
  70946. if (this._gamepadSupport) {
  70947. //first add already-connected gamepads
  70948. this._updateGamepadObjects();
  70949. if (this._babylonGamepads.length) {
  70950. this._startMonitoringGamepads();
  70951. }
  70952. // Checking if the gamepad connected event is supported (like in Firefox)
  70953. if (this._gamepadEventSupported) {
  70954. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70955. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70956. }
  70957. else {
  70958. this._startMonitoringGamepads();
  70959. }
  70960. }
  70961. }
  70962. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70963. get: function () {
  70964. return this._babylonGamepads;
  70965. },
  70966. enumerable: true,
  70967. configurable: true
  70968. });
  70969. GamepadManager.prototype.getGamepadByType = function (type) {
  70970. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70971. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70972. var gamepad = _a[_i];
  70973. if (gamepad && gamepad.type === type) {
  70974. return gamepad;
  70975. }
  70976. }
  70977. return null;
  70978. };
  70979. GamepadManager.prototype.dispose = function () {
  70980. if (this._gamepadEventSupported) {
  70981. if (this._onGamepadConnectedEvent) {
  70982. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70983. }
  70984. if (this._onGamepadDisconnectedEvent) {
  70985. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70986. }
  70987. this._onGamepadConnectedEvent = null;
  70988. this._onGamepadDisconnectedEvent = null;
  70989. }
  70990. this._babylonGamepads.forEach(function (gamepad) {
  70991. gamepad.dispose();
  70992. });
  70993. this.onGamepadConnectedObservable.clear();
  70994. this.onGamepadDisconnectedObservable.clear();
  70995. this._oneGamepadConnected = false;
  70996. this._stopMonitoringGamepads();
  70997. this._babylonGamepads = [];
  70998. };
  70999. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71000. if (!this._oneGamepadConnected) {
  71001. this._oneGamepadConnected = true;
  71002. }
  71003. var newGamepad;
  71004. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71005. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71006. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71007. }
  71008. // if pose is supported, use the (WebVR) pose enabled controller
  71009. else if (gamepad.pose) {
  71010. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71011. }
  71012. else {
  71013. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71014. }
  71015. this._babylonGamepads[newGamepad.index] = newGamepad;
  71016. return newGamepad;
  71017. };
  71018. GamepadManager.prototype._startMonitoringGamepads = function () {
  71019. if (!this._isMonitoring) {
  71020. this._isMonitoring = true;
  71021. //back-comp
  71022. if (!this._scene) {
  71023. this._checkGamepadsStatus();
  71024. }
  71025. }
  71026. };
  71027. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71028. this._isMonitoring = false;
  71029. };
  71030. GamepadManager.prototype._checkGamepadsStatus = function () {
  71031. var _this = this;
  71032. // Hack to be compatible Chrome
  71033. this._updateGamepadObjects();
  71034. for (var i in this._babylonGamepads) {
  71035. var gamepad = this._babylonGamepads[i];
  71036. if (!gamepad || !gamepad.isConnected) {
  71037. continue;
  71038. }
  71039. gamepad.update();
  71040. }
  71041. if (this._isMonitoring && !this._scene) {
  71042. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71043. }
  71044. };
  71045. // This function is called only on Chrome, which does not properly support
  71046. // connection/disconnection events and forces you to recopy again the gamepad object
  71047. GamepadManager.prototype._updateGamepadObjects = function () {
  71048. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71049. for (var i = 0; i < gamepads.length; i++) {
  71050. var gamepad = gamepads[i];
  71051. if (gamepad) {
  71052. if (!this._babylonGamepads[gamepad.index]) {
  71053. var newGamepad = this._addNewGamepad(gamepad);
  71054. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71055. }
  71056. else {
  71057. // Forced to copy again this object for Chrome for unknown reason
  71058. this._babylonGamepads[i].browserGamepad = gamepad;
  71059. if (!this._babylonGamepads[i].isConnected) {
  71060. this._babylonGamepads[i]._isConnected = true;
  71061. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71062. }
  71063. }
  71064. }
  71065. }
  71066. };
  71067. return GamepadManager;
  71068. }());
  71069. BABYLON.GamepadManager = GamepadManager;
  71070. })(BABYLON || (BABYLON = {}));
  71071. //# sourceMappingURL=babylon.gamepadManager.js.map
  71072. var BABYLON;
  71073. (function (BABYLON) {
  71074. var StickValues = /** @class */ (function () {
  71075. function StickValues(x, y) {
  71076. this.x = x;
  71077. this.y = y;
  71078. }
  71079. return StickValues;
  71080. }());
  71081. BABYLON.StickValues = StickValues;
  71082. var Gamepad = /** @class */ (function () {
  71083. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71084. if (leftStickX === void 0) { leftStickX = 0; }
  71085. if (leftStickY === void 0) { leftStickY = 1; }
  71086. if (rightStickX === void 0) { rightStickX = 2; }
  71087. if (rightStickY === void 0) { rightStickY = 3; }
  71088. this.id = id;
  71089. this.index = index;
  71090. this.browserGamepad = browserGamepad;
  71091. this._isConnected = true;
  71092. this._invertLeftStickY = false;
  71093. this.type = Gamepad.GAMEPAD;
  71094. this._leftStickAxisX = leftStickX;
  71095. this._leftStickAxisY = leftStickY;
  71096. this._rightStickAxisX = rightStickX;
  71097. this._rightStickAxisY = rightStickY;
  71098. if (this.browserGamepad.axes.length >= 2) {
  71099. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71100. }
  71101. if (this.browserGamepad.axes.length >= 4) {
  71102. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71103. }
  71104. }
  71105. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71106. get: function () {
  71107. return this._isConnected;
  71108. },
  71109. enumerable: true,
  71110. configurable: true
  71111. });
  71112. Gamepad.prototype.onleftstickchanged = function (callback) {
  71113. this._onleftstickchanged = callback;
  71114. };
  71115. Gamepad.prototype.onrightstickchanged = function (callback) {
  71116. this._onrightstickchanged = callback;
  71117. };
  71118. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71119. get: function () {
  71120. return this._leftStick;
  71121. },
  71122. set: function (newValues) {
  71123. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71124. this._onleftstickchanged(newValues);
  71125. }
  71126. this._leftStick = newValues;
  71127. },
  71128. enumerable: true,
  71129. configurable: true
  71130. });
  71131. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71132. get: function () {
  71133. return this._rightStick;
  71134. },
  71135. set: function (newValues) {
  71136. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71137. this._onrightstickchanged(newValues);
  71138. }
  71139. this._rightStick = newValues;
  71140. },
  71141. enumerable: true,
  71142. configurable: true
  71143. });
  71144. Gamepad.prototype.update = function () {
  71145. if (this._leftStick) {
  71146. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71147. if (this._invertLeftStickY) {
  71148. this.leftStick.y *= -1;
  71149. }
  71150. }
  71151. if (this._rightStick) {
  71152. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71153. }
  71154. };
  71155. Gamepad.prototype.dispose = function () {
  71156. };
  71157. Gamepad.GAMEPAD = 0;
  71158. Gamepad.GENERIC = 1;
  71159. Gamepad.XBOX = 2;
  71160. Gamepad.POSE_ENABLED = 3;
  71161. return Gamepad;
  71162. }());
  71163. BABYLON.Gamepad = Gamepad;
  71164. var GenericPad = /** @class */ (function (_super) {
  71165. __extends(GenericPad, _super);
  71166. function GenericPad(id, index, browserGamepad) {
  71167. var _this = _super.call(this, id, index, browserGamepad) || this;
  71168. _this.onButtonDownObservable = new BABYLON.Observable();
  71169. _this.onButtonUpObservable = new BABYLON.Observable();
  71170. _this.type = Gamepad.GENERIC;
  71171. _this._buttons = new Array(browserGamepad.buttons.length);
  71172. return _this;
  71173. }
  71174. GenericPad.prototype.onbuttondown = function (callback) {
  71175. this._onbuttondown = callback;
  71176. };
  71177. GenericPad.prototype.onbuttonup = function (callback) {
  71178. this._onbuttonup = callback;
  71179. };
  71180. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71181. if (newValue !== currentValue) {
  71182. if (newValue === 1) {
  71183. if (this._onbuttondown) {
  71184. this._onbuttondown(buttonIndex);
  71185. }
  71186. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71187. }
  71188. if (newValue === 0) {
  71189. if (this._onbuttonup) {
  71190. this._onbuttonup(buttonIndex);
  71191. }
  71192. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71193. }
  71194. }
  71195. return newValue;
  71196. };
  71197. GenericPad.prototype.update = function () {
  71198. _super.prototype.update.call(this);
  71199. for (var index = 0; index < this._buttons.length; index++) {
  71200. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71201. }
  71202. };
  71203. GenericPad.prototype.dispose = function () {
  71204. _super.prototype.dispose.call(this);
  71205. this.onButtonDownObservable.clear();
  71206. this.onButtonUpObservable.clear();
  71207. };
  71208. return GenericPad;
  71209. }(Gamepad));
  71210. BABYLON.GenericPad = GenericPad;
  71211. })(BABYLON || (BABYLON = {}));
  71212. //# sourceMappingURL=babylon.gamepad.js.map
  71213. var BABYLON;
  71214. (function (BABYLON) {
  71215. /**
  71216. * Defines supported buttons for XBox360 compatible gamepads
  71217. */
  71218. var Xbox360Button;
  71219. (function (Xbox360Button) {
  71220. /** A */
  71221. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71222. /** B */
  71223. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71224. /** X */
  71225. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71226. /** Y */
  71227. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71228. /** Start */
  71229. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71230. /** Back */
  71231. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71232. /** Left button */
  71233. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71234. /** Right button */
  71235. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71236. /** Left stick */
  71237. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71238. /** Right stick */
  71239. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71240. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71241. /** Defines values for XBox360 DPad */
  71242. var Xbox360Dpad;
  71243. (function (Xbox360Dpad) {
  71244. /** Up */
  71245. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71246. /** Down */
  71247. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71248. /** Left */
  71249. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71250. /** Right */
  71251. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71252. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71253. /**
  71254. * Defines a XBox360 gamepad
  71255. */
  71256. var Xbox360Pad = /** @class */ (function (_super) {
  71257. __extends(Xbox360Pad, _super);
  71258. /**
  71259. * Creates a new XBox360 gamepad object
  71260. * @param id defines the id of this gamepad
  71261. * @param index defines its index
  71262. * @param gamepad defines the internal HTML gamepad object
  71263. * @param xboxOne defines if it is a XBox One gamepad
  71264. */
  71265. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71266. if (xboxOne === void 0) { xboxOne = false; }
  71267. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71268. _this._leftTrigger = 0;
  71269. _this._rightTrigger = 0;
  71270. /** Observable raised when a button is pressed */
  71271. _this.onButtonDownObservable = new BABYLON.Observable();
  71272. /** Observable raised when a button is released */
  71273. _this.onButtonUpObservable = new BABYLON.Observable();
  71274. /** Observable raised when a pad is pressed */
  71275. _this.onPadDownObservable = new BABYLON.Observable();
  71276. /** Observable raised when a pad is released */
  71277. _this.onPadUpObservable = new BABYLON.Observable();
  71278. _this._buttonA = 0;
  71279. _this._buttonB = 0;
  71280. _this._buttonX = 0;
  71281. _this._buttonY = 0;
  71282. _this._buttonBack = 0;
  71283. _this._buttonStart = 0;
  71284. _this._buttonLB = 0;
  71285. _this._buttonRB = 0;
  71286. _this._buttonLeftStick = 0;
  71287. _this._buttonRightStick = 0;
  71288. _this._dPadUp = 0;
  71289. _this._dPadDown = 0;
  71290. _this._dPadLeft = 0;
  71291. _this._dPadRight = 0;
  71292. _this._isXboxOnePad = false;
  71293. _this.type = BABYLON.Gamepad.XBOX;
  71294. _this._isXboxOnePad = xboxOne;
  71295. return _this;
  71296. }
  71297. /**
  71298. * Defines the callback to call when left trigger is pressed
  71299. * @param callback defines the callback to use
  71300. */
  71301. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71302. this._onlefttriggerchanged = callback;
  71303. };
  71304. /**
  71305. * Defines the callback to call when right trigger is pressed
  71306. * @param callback defines the callback to use
  71307. */
  71308. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71309. this._onrighttriggerchanged = callback;
  71310. };
  71311. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71312. /**
  71313. * Gets or sets left trigger value
  71314. */
  71315. get: function () {
  71316. return this._leftTrigger;
  71317. },
  71318. set: function (newValue) {
  71319. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71320. this._onlefttriggerchanged(newValue);
  71321. }
  71322. this._leftTrigger = newValue;
  71323. },
  71324. enumerable: true,
  71325. configurable: true
  71326. });
  71327. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71328. /**
  71329. * Gets or sets right trigger value
  71330. */
  71331. get: function () {
  71332. return this._rightTrigger;
  71333. },
  71334. set: function (newValue) {
  71335. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71336. this._onrighttriggerchanged(newValue);
  71337. }
  71338. this._rightTrigger = newValue;
  71339. },
  71340. enumerable: true,
  71341. configurable: true
  71342. });
  71343. /**
  71344. * Defines the callback to call when a button is pressed
  71345. * @param callback defines the callback to use
  71346. */
  71347. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71348. this._onbuttondown = callback;
  71349. };
  71350. /**
  71351. * Defines the callback to call when a button is released
  71352. * @param callback defines the callback to use
  71353. */
  71354. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71355. this._onbuttonup = callback;
  71356. };
  71357. /**
  71358. * Defines the callback to call when a pad is pressed
  71359. * @param callback defines the callback to use
  71360. */
  71361. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71362. this._ondpaddown = callback;
  71363. };
  71364. /**
  71365. * Defines the callback to call when a pad is released
  71366. * @param callback defines the callback to use
  71367. */
  71368. Xbox360Pad.prototype.ondpadup = function (callback) {
  71369. this._ondpadup = callback;
  71370. };
  71371. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71372. if (newValue !== currentValue) {
  71373. if (newValue === 1) {
  71374. if (this._onbuttondown) {
  71375. this._onbuttondown(buttonType);
  71376. }
  71377. this.onButtonDownObservable.notifyObservers(buttonType);
  71378. }
  71379. if (newValue === 0) {
  71380. if (this._onbuttonup) {
  71381. this._onbuttonup(buttonType);
  71382. }
  71383. this.onButtonUpObservable.notifyObservers(buttonType);
  71384. }
  71385. }
  71386. return newValue;
  71387. };
  71388. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71389. if (newValue !== currentValue) {
  71390. if (newValue === 1) {
  71391. if (this._ondpaddown) {
  71392. this._ondpaddown(buttonType);
  71393. }
  71394. this.onPadDownObservable.notifyObservers(buttonType);
  71395. }
  71396. if (newValue === 0) {
  71397. if (this._ondpadup) {
  71398. this._ondpadup(buttonType);
  71399. }
  71400. this.onPadUpObservable.notifyObservers(buttonType);
  71401. }
  71402. }
  71403. return newValue;
  71404. };
  71405. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71406. /** Gets or sets value of A button */
  71407. get: function () {
  71408. return this._buttonA;
  71409. },
  71410. set: function (value) {
  71411. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71412. },
  71413. enumerable: true,
  71414. configurable: true
  71415. });
  71416. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71417. /** Gets or sets value of B button */
  71418. get: function () {
  71419. return this._buttonB;
  71420. },
  71421. set: function (value) {
  71422. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71423. },
  71424. enumerable: true,
  71425. configurable: true
  71426. });
  71427. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71428. /** Gets or sets value of X button */
  71429. get: function () {
  71430. return this._buttonX;
  71431. },
  71432. set: function (value) {
  71433. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71434. },
  71435. enumerable: true,
  71436. configurable: true
  71437. });
  71438. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71439. /** Gets or sets value of Y button */
  71440. get: function () {
  71441. return this._buttonY;
  71442. },
  71443. set: function (value) {
  71444. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71445. },
  71446. enumerable: true,
  71447. configurable: true
  71448. });
  71449. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71450. /** Gets or sets value of Start button */
  71451. get: function () {
  71452. return this._buttonStart;
  71453. },
  71454. set: function (value) {
  71455. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71456. },
  71457. enumerable: true,
  71458. configurable: true
  71459. });
  71460. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71461. /** Gets or sets value of Back button */
  71462. get: function () {
  71463. return this._buttonBack;
  71464. },
  71465. set: function (value) {
  71466. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71467. },
  71468. enumerable: true,
  71469. configurable: true
  71470. });
  71471. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71472. /** Gets or sets value of Left button */
  71473. get: function () {
  71474. return this._buttonLB;
  71475. },
  71476. set: function (value) {
  71477. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71478. },
  71479. enumerable: true,
  71480. configurable: true
  71481. });
  71482. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71483. /** Gets or sets value of Right button */
  71484. get: function () {
  71485. return this._buttonRB;
  71486. },
  71487. set: function (value) {
  71488. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71489. },
  71490. enumerable: true,
  71491. configurable: true
  71492. });
  71493. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71494. /** Gets or sets value of left stick */
  71495. get: function () {
  71496. return this._buttonLeftStick;
  71497. },
  71498. set: function (value) {
  71499. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71500. },
  71501. enumerable: true,
  71502. configurable: true
  71503. });
  71504. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71505. /** Gets or sets value of right stick */
  71506. get: function () {
  71507. return this._buttonRightStick;
  71508. },
  71509. set: function (value) {
  71510. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71511. },
  71512. enumerable: true,
  71513. configurable: true
  71514. });
  71515. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71516. /** Gets or sets value of DPad up */
  71517. get: function () {
  71518. return this._dPadUp;
  71519. },
  71520. set: function (value) {
  71521. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71522. },
  71523. enumerable: true,
  71524. configurable: true
  71525. });
  71526. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71527. /** Gets or sets value of DPad down */
  71528. get: function () {
  71529. return this._dPadDown;
  71530. },
  71531. set: function (value) {
  71532. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71533. },
  71534. enumerable: true,
  71535. configurable: true
  71536. });
  71537. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71538. /** Gets or sets value of DPad left */
  71539. get: function () {
  71540. return this._dPadLeft;
  71541. },
  71542. set: function (value) {
  71543. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71544. },
  71545. enumerable: true,
  71546. configurable: true
  71547. });
  71548. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71549. /** Gets or sets value of DPad right */
  71550. get: function () {
  71551. return this._dPadRight;
  71552. },
  71553. set: function (value) {
  71554. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71555. },
  71556. enumerable: true,
  71557. configurable: true
  71558. });
  71559. /**
  71560. * Force the gamepad to synchronize with device values
  71561. */
  71562. Xbox360Pad.prototype.update = function () {
  71563. _super.prototype.update.call(this);
  71564. if (this._isXboxOnePad) {
  71565. this.buttonA = this.browserGamepad.buttons[0].value;
  71566. this.buttonB = this.browserGamepad.buttons[1].value;
  71567. this.buttonX = this.browserGamepad.buttons[2].value;
  71568. this.buttonY = this.browserGamepad.buttons[3].value;
  71569. this.buttonLB = this.browserGamepad.buttons[4].value;
  71570. this.buttonRB = this.browserGamepad.buttons[5].value;
  71571. this.leftTrigger = this.browserGamepad.axes[2];
  71572. this.rightTrigger = this.browserGamepad.axes[5];
  71573. this.buttonBack = this.browserGamepad.buttons[9].value;
  71574. this.buttonStart = this.browserGamepad.buttons[8].value;
  71575. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71576. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71577. this.dPadUp = this.browserGamepad.buttons[11].value;
  71578. this.dPadDown = this.browserGamepad.buttons[12].value;
  71579. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71580. this.dPadRight = this.browserGamepad.buttons[14].value;
  71581. }
  71582. else {
  71583. this.buttonA = this.browserGamepad.buttons[0].value;
  71584. this.buttonB = this.browserGamepad.buttons[1].value;
  71585. this.buttonX = this.browserGamepad.buttons[2].value;
  71586. this.buttonY = this.browserGamepad.buttons[3].value;
  71587. this.buttonLB = this.browserGamepad.buttons[4].value;
  71588. this.buttonRB = this.browserGamepad.buttons[5].value;
  71589. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71590. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71591. this.buttonBack = this.browserGamepad.buttons[8].value;
  71592. this.buttonStart = this.browserGamepad.buttons[9].value;
  71593. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71594. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71595. this.dPadUp = this.browserGamepad.buttons[12].value;
  71596. this.dPadDown = this.browserGamepad.buttons[13].value;
  71597. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71598. this.dPadRight = this.browserGamepad.buttons[15].value;
  71599. }
  71600. };
  71601. Xbox360Pad.prototype.dispose = function () {
  71602. _super.prototype.dispose.call(this);
  71603. this.onButtonDownObservable.clear();
  71604. this.onButtonUpObservable.clear();
  71605. this.onPadDownObservable.clear();
  71606. this.onPadUpObservable.clear();
  71607. };
  71608. return Xbox360Pad;
  71609. }(BABYLON.Gamepad));
  71610. BABYLON.Xbox360Pad = Xbox360Pad;
  71611. })(BABYLON || (BABYLON = {}));
  71612. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71613. var BABYLON;
  71614. (function (BABYLON) {
  71615. /**
  71616. * Defines the types of pose enabled controllers that are supported
  71617. */
  71618. var PoseEnabledControllerType;
  71619. (function (PoseEnabledControllerType) {
  71620. /**
  71621. * HTC Vive
  71622. */
  71623. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71624. /**
  71625. * Oculus Rift
  71626. */
  71627. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71628. /**
  71629. * Windows mixed reality
  71630. */
  71631. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71632. /**
  71633. * Samsung gear VR
  71634. */
  71635. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71636. /**
  71637. * Google Daydream
  71638. */
  71639. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71640. /**
  71641. * Generic
  71642. */
  71643. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71644. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71645. /**
  71646. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71647. */
  71648. var PoseEnabledControllerHelper = /** @class */ (function () {
  71649. function PoseEnabledControllerHelper() {
  71650. }
  71651. /**
  71652. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71653. * @param vrGamepad the gamepad to initialized
  71654. * @returns a vr controller of the type the gamepad identified as
  71655. */
  71656. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71657. // Oculus Touch
  71658. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71659. return new BABYLON.OculusTouchController(vrGamepad);
  71660. }
  71661. // Windows Mixed Reality controllers
  71662. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71663. return new BABYLON.WindowsMotionController(vrGamepad);
  71664. }
  71665. // HTC Vive
  71666. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71667. return new BABYLON.ViveController(vrGamepad);
  71668. }
  71669. // Samsung/Oculus Gear VR or Oculus Go
  71670. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71671. return new BABYLON.GearVRController(vrGamepad);
  71672. }
  71673. // Google Daydream
  71674. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71675. return new BABYLON.DaydreamController(vrGamepad);
  71676. }
  71677. // Generic
  71678. else {
  71679. return new BABYLON.GenericController(vrGamepad);
  71680. }
  71681. };
  71682. return PoseEnabledControllerHelper;
  71683. }());
  71684. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71685. /**
  71686. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71687. */
  71688. var PoseEnabledController = /** @class */ (function (_super) {
  71689. __extends(PoseEnabledController, _super);
  71690. /**
  71691. * Creates a new PoseEnabledController from a gamepad
  71692. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71693. */
  71694. function PoseEnabledController(browserGamepad) {
  71695. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71696. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71697. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71698. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71699. /**
  71700. * The device position in babylon space
  71701. */
  71702. _this.devicePosition = BABYLON.Vector3.Zero();
  71703. /**
  71704. * The device rotation in babylon space
  71705. */
  71706. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71707. /**
  71708. * The scale factor of the device in babylon space
  71709. */
  71710. _this.deviceScaleFactor = 1;
  71711. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71712. /**
  71713. * Internal, matrix used to convert room space to babylon space
  71714. */
  71715. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71716. /**
  71717. * Node to be used when casting a ray from the controller
  71718. */
  71719. _this._pointingPoseNode = null;
  71720. _this._workingMatrix = BABYLON.Matrix.Identity();
  71721. /**
  71722. * @hidden
  71723. */
  71724. _this._meshAttachedObservable = new BABYLON.Observable();
  71725. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71726. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71727. _this.position = BABYLON.Vector3.Zero();
  71728. _this.rotationQuaternion = new BABYLON.Quaternion();
  71729. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71730. _this._calculatedRotation = new BABYLON.Quaternion();
  71731. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71732. return _this;
  71733. }
  71734. /**
  71735. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71736. */
  71737. PoseEnabledController.prototype.update = function () {
  71738. _super.prototype.update.call(this);
  71739. var pose = this.browserGamepad.pose;
  71740. this.updateFromDevice(pose);
  71741. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71742. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71743. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71744. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71745. if (this._mesh) {
  71746. this._mesh.position.copyFrom(this.devicePosition);
  71747. if (this._mesh.rotationQuaternion) {
  71748. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71749. }
  71750. }
  71751. };
  71752. /**
  71753. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71754. * @param poseData raw pose fromthe device
  71755. */
  71756. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71757. if (poseData) {
  71758. this.rawPose = poseData;
  71759. if (poseData.position) {
  71760. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71761. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71762. this._deviceRoomPosition.z *= -1;
  71763. }
  71764. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71765. this._calculatedPosition.addInPlace(this.position);
  71766. }
  71767. var pose = this.rawPose;
  71768. if (poseData.orientation && pose.orientation) {
  71769. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71770. if (this._mesh) {
  71771. if (this._mesh.getScene().useRightHandedSystem) {
  71772. this._deviceRoomRotationQuaternion.z *= -1;
  71773. this._deviceRoomRotationQuaternion.w *= -1;
  71774. }
  71775. else {
  71776. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71777. }
  71778. }
  71779. // if the camera is set, rotate to the camera's rotation
  71780. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71781. }
  71782. }
  71783. };
  71784. /**
  71785. * Attaches a mesh to the controller
  71786. * @param mesh the mesh to be attached
  71787. */
  71788. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71789. if (this._mesh) {
  71790. this._mesh.parent = null;
  71791. }
  71792. this._mesh = mesh;
  71793. if (this._poseControlledCamera) {
  71794. this._mesh.parent = this._poseControlledCamera;
  71795. }
  71796. if (!this._mesh.rotationQuaternion) {
  71797. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71798. }
  71799. this._meshAttachedObservable.notifyObservers(mesh);
  71800. };
  71801. /**
  71802. * Attaches the controllers mesh to a camera
  71803. * @param camera the camera the mesh should be attached to
  71804. */
  71805. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71806. this._poseControlledCamera = camera;
  71807. if (this._mesh) {
  71808. this._mesh.parent = this._poseControlledCamera;
  71809. }
  71810. };
  71811. /**
  71812. * Disposes of the controller
  71813. */
  71814. PoseEnabledController.prototype.dispose = function () {
  71815. if (this._mesh) {
  71816. this._mesh.dispose();
  71817. }
  71818. this._mesh = null;
  71819. _super.prototype.dispose.call(this);
  71820. };
  71821. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71822. /**
  71823. * The mesh that is attached to the controller
  71824. */
  71825. get: function () {
  71826. return this._mesh;
  71827. },
  71828. enumerable: true,
  71829. configurable: true
  71830. });
  71831. /**
  71832. * Gets the ray of the controller in the direction the controller is pointing
  71833. * @param length the length the resulting ray should be
  71834. * @returns a ray in the direction the controller is pointing
  71835. */
  71836. PoseEnabledController.prototype.getForwardRay = function (length) {
  71837. if (length === void 0) { length = 100; }
  71838. if (!this.mesh) {
  71839. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71840. }
  71841. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71842. var origin = m.getTranslation();
  71843. var forward = new BABYLON.Vector3(0, 0, -1);
  71844. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71845. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71846. return new BABYLON.Ray(origin, direction, length);
  71847. };
  71848. /**
  71849. * Name of the child mesh that can be used to cast a ray from the controller
  71850. */
  71851. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71852. return PoseEnabledController;
  71853. }(BABYLON.Gamepad));
  71854. BABYLON.PoseEnabledController = PoseEnabledController;
  71855. })(BABYLON || (BABYLON = {}));
  71856. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71857. var BABYLON;
  71858. (function (BABYLON) {
  71859. /**
  71860. * Defines the WebVRController object that represents controllers tracked in 3D space
  71861. */
  71862. var WebVRController = /** @class */ (function (_super) {
  71863. __extends(WebVRController, _super);
  71864. /**
  71865. * Creates a new WebVRController from a gamepad
  71866. * @param vrGamepad the gamepad that the WebVRController should be created from
  71867. */
  71868. function WebVRController(vrGamepad) {
  71869. var _this = _super.call(this, vrGamepad) || this;
  71870. // Observables
  71871. /**
  71872. * Fired when the trigger state has changed
  71873. */
  71874. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71875. /**
  71876. * Fired when the main button state has changed
  71877. */
  71878. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71879. /**
  71880. * Fired when the secondary button state has changed
  71881. */
  71882. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71883. /**
  71884. * Fired when the pad state has changed
  71885. */
  71886. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71887. /**
  71888. * Fired when controllers stick values have changed
  71889. */
  71890. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71891. /**
  71892. * X and Y axis corrisponding to the controllers joystick
  71893. */
  71894. _this.pad = { x: 0, y: 0 };
  71895. // avoid GC, store state in a tmp object
  71896. _this._changes = {
  71897. pressChanged: false,
  71898. touchChanged: false,
  71899. valueChanged: false,
  71900. changed: false
  71901. };
  71902. _this._buttons = new Array(vrGamepad.buttons.length);
  71903. _this.hand = vrGamepad.hand;
  71904. return _this;
  71905. }
  71906. /**
  71907. * Fired when a controller button's state has changed
  71908. * @param callback the callback containing the button that was modified
  71909. */
  71910. WebVRController.prototype.onButtonStateChange = function (callback) {
  71911. this._onButtonStateChange = callback;
  71912. };
  71913. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71914. /**
  71915. * The default controller model for the controller
  71916. */
  71917. get: function () {
  71918. return this._defaultModel;
  71919. },
  71920. enumerable: true,
  71921. configurable: true
  71922. });
  71923. /**
  71924. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71925. */
  71926. WebVRController.prototype.update = function () {
  71927. _super.prototype.update.call(this);
  71928. for (var index = 0; index < this._buttons.length; index++) {
  71929. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71930. }
  71931. ;
  71932. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71933. this.pad.x = this.leftStick.x;
  71934. this.pad.y = this.leftStick.y;
  71935. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71936. }
  71937. };
  71938. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71939. if (!newState) {
  71940. newState = {
  71941. pressed: false,
  71942. touched: false,
  71943. value: 0
  71944. };
  71945. }
  71946. if (!currentState) {
  71947. this._buttons[buttonIndex] = {
  71948. pressed: newState.pressed,
  71949. touched: newState.touched,
  71950. value: newState.value
  71951. };
  71952. return;
  71953. }
  71954. this._checkChanges(newState, currentState);
  71955. if (this._changes.changed) {
  71956. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71957. this._handleButtonChange(buttonIndex, newState, this._changes);
  71958. }
  71959. this._buttons[buttonIndex].pressed = newState.pressed;
  71960. this._buttons[buttonIndex].touched = newState.touched;
  71961. // oculus triggers are never 0, thou not touched.
  71962. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71963. };
  71964. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71965. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71966. this._changes.touchChanged = newState.touched !== currentState.touched;
  71967. this._changes.valueChanged = newState.value !== currentState.value;
  71968. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71969. return this._changes;
  71970. };
  71971. /**
  71972. * Disposes of th webVRCOntroller
  71973. */
  71974. WebVRController.prototype.dispose = function () {
  71975. _super.prototype.dispose.call(this);
  71976. this.onTriggerStateChangedObservable.clear();
  71977. this.onMainButtonStateChangedObservable.clear();
  71978. this.onSecondaryButtonStateChangedObservable.clear();
  71979. this.onPadStateChangedObservable.clear();
  71980. this.onPadValuesChangedObservable.clear();
  71981. };
  71982. return WebVRController;
  71983. }(BABYLON.PoseEnabledController));
  71984. BABYLON.WebVRController = WebVRController;
  71985. })(BABYLON || (BABYLON = {}));
  71986. //# sourceMappingURL=babylon.webVRController.js.map
  71987. var BABYLON;
  71988. (function (BABYLON) {
  71989. /**
  71990. * Oculus Touch Controller
  71991. */
  71992. var OculusTouchController = /** @class */ (function (_super) {
  71993. __extends(OculusTouchController, _super);
  71994. /**
  71995. * Creates a new OculusTouchController from a gamepad
  71996. * @param vrGamepad the gamepad that the controller should be created from
  71997. */
  71998. function OculusTouchController(vrGamepad) {
  71999. var _this = _super.call(this, vrGamepad) || this;
  72000. /**
  72001. * Fired when the secondary trigger on this controller is modified
  72002. */
  72003. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72004. /**
  72005. * Fired when the thumb rest on this controller is modified
  72006. */
  72007. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72008. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72009. return _this;
  72010. }
  72011. /**
  72012. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72013. * @param scene scene in which to add meshes
  72014. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72015. */
  72016. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72017. var _this = this;
  72018. var meshName;
  72019. // Hand
  72020. if (this.hand === 'left') {
  72021. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72022. }
  72023. else { // Right is the default if no hand is specified
  72024. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72025. }
  72026. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72027. /*
  72028. Parent Mesh name: oculus_touch_left
  72029. - body
  72030. - trigger
  72031. - thumbstick
  72032. - grip
  72033. - button_y
  72034. - button_x
  72035. - button_enter
  72036. */
  72037. _this._defaultModel = newMeshes[1];
  72038. _this.attachToMesh(_this._defaultModel);
  72039. if (meshLoaded) {
  72040. meshLoaded(_this._defaultModel);
  72041. }
  72042. });
  72043. };
  72044. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72045. /**
  72046. * Fired when the A button on this controller is modified
  72047. */
  72048. get: function () {
  72049. if (this.hand === 'right') {
  72050. return this.onMainButtonStateChangedObservable;
  72051. }
  72052. else {
  72053. throw new Error('No A button on left hand');
  72054. }
  72055. },
  72056. enumerable: true,
  72057. configurable: true
  72058. });
  72059. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72060. /**
  72061. * Fired when the B button on this controller is modified
  72062. */
  72063. get: function () {
  72064. if (this.hand === 'right') {
  72065. return this.onSecondaryButtonStateChangedObservable;
  72066. }
  72067. else {
  72068. throw new Error('No B button on left hand');
  72069. }
  72070. },
  72071. enumerable: true,
  72072. configurable: true
  72073. });
  72074. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72075. /**
  72076. * Fired when the X button on this controller is modified
  72077. */
  72078. get: function () {
  72079. if (this.hand === 'left') {
  72080. return this.onMainButtonStateChangedObservable;
  72081. }
  72082. else {
  72083. throw new Error('No X button on right hand');
  72084. }
  72085. },
  72086. enumerable: true,
  72087. configurable: true
  72088. });
  72089. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72090. /**
  72091. * Fired when the Y button on this controller is modified
  72092. */
  72093. get: function () {
  72094. if (this.hand === 'left') {
  72095. return this.onSecondaryButtonStateChangedObservable;
  72096. }
  72097. else {
  72098. throw new Error('No Y button on right hand');
  72099. }
  72100. },
  72101. enumerable: true,
  72102. configurable: true
  72103. });
  72104. /**
  72105. * Called once for each button that changed state since the last frame
  72106. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72107. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72108. * 2) secondary trigger (same)
  72109. * 3) A (right) X (left), touch, pressed = value
  72110. * 4) B / Y
  72111. * 5) thumb rest
  72112. * @param buttonIdx Which button index changed
  72113. * @param state New state of the button
  72114. * @param changes Which properties on the state changed since last frame
  72115. */
  72116. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72117. var notifyObject = state; //{ state: state, changes: changes };
  72118. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72119. switch (buttonIdx) {
  72120. case 0:
  72121. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72122. return;
  72123. case 1: // index trigger
  72124. if (this._defaultModel) {
  72125. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72126. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72127. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72128. }
  72129. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72130. return;
  72131. case 2: // secondary trigger
  72132. if (this._defaultModel) {
  72133. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72134. }
  72135. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72136. return;
  72137. case 3:
  72138. if (this._defaultModel) {
  72139. if (notifyObject.pressed) {
  72140. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72141. }
  72142. else {
  72143. (this._defaultModel.getChildren()[1]).position.y = 0;
  72144. }
  72145. }
  72146. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72147. return;
  72148. case 4:
  72149. if (this._defaultModel) {
  72150. if (notifyObject.pressed) {
  72151. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72152. }
  72153. else {
  72154. (this._defaultModel.getChildren()[2]).position.y = 0;
  72155. }
  72156. }
  72157. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72158. return;
  72159. case 5:
  72160. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72161. return;
  72162. }
  72163. };
  72164. /**
  72165. * Base Url for the controller model.
  72166. */
  72167. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72168. /**
  72169. * File name for the left controller model.
  72170. */
  72171. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72172. /**
  72173. * File name for the right controller model.
  72174. */
  72175. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72176. return OculusTouchController;
  72177. }(BABYLON.WebVRController));
  72178. BABYLON.OculusTouchController = OculusTouchController;
  72179. })(BABYLON || (BABYLON = {}));
  72180. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72181. var BABYLON;
  72182. (function (BABYLON) {
  72183. /**
  72184. * Vive Controller
  72185. */
  72186. var ViveController = /** @class */ (function (_super) {
  72187. __extends(ViveController, _super);
  72188. /**
  72189. * Creates a new ViveController from a gamepad
  72190. * @param vrGamepad the gamepad that the controller should be created from
  72191. */
  72192. function ViveController(vrGamepad) {
  72193. var _this = _super.call(this, vrGamepad) || this;
  72194. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72195. _this._invertLeftStickY = true;
  72196. return _this;
  72197. }
  72198. /**
  72199. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72200. * @param scene scene in which to add meshes
  72201. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72202. */
  72203. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72204. var _this = this;
  72205. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72206. /*
  72207. Parent Mesh name: ViveWand
  72208. - body
  72209. - r_gripper
  72210. - l_gripper
  72211. - menu_button
  72212. - system_button
  72213. - trackpad
  72214. - trigger
  72215. - LED
  72216. */
  72217. _this._defaultModel = newMeshes[1];
  72218. _this.attachToMesh(_this._defaultModel);
  72219. if (meshLoaded) {
  72220. meshLoaded(_this._defaultModel);
  72221. }
  72222. });
  72223. };
  72224. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72225. /**
  72226. * Fired when the left button on this controller is modified
  72227. */
  72228. get: function () {
  72229. return this.onMainButtonStateChangedObservable;
  72230. },
  72231. enumerable: true,
  72232. configurable: true
  72233. });
  72234. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72235. /**
  72236. * Fired when the right button on this controller is modified
  72237. */
  72238. get: function () {
  72239. return this.onMainButtonStateChangedObservable;
  72240. },
  72241. enumerable: true,
  72242. configurable: true
  72243. });
  72244. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72245. /**
  72246. * Fired when the menu button on this controller is modified
  72247. */
  72248. get: function () {
  72249. return this.onSecondaryButtonStateChangedObservable;
  72250. },
  72251. enumerable: true,
  72252. configurable: true
  72253. });
  72254. /**
  72255. * Called once for each button that changed state since the last frame
  72256. * Vive mapping:
  72257. * 0: touchpad
  72258. * 1: trigger
  72259. * 2: left AND right buttons
  72260. * 3: menu button
  72261. * @param buttonIdx Which button index changed
  72262. * @param state New state of the button
  72263. * @param changes Which properties on the state changed since last frame
  72264. */
  72265. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72266. var notifyObject = state; //{ state: state, changes: changes };
  72267. switch (buttonIdx) {
  72268. case 0:
  72269. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72270. return;
  72271. case 1: // index trigger
  72272. if (this._defaultModel) {
  72273. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72274. }
  72275. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72276. return;
  72277. case 2: // left AND right button
  72278. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72279. return;
  72280. case 3:
  72281. if (this._defaultModel) {
  72282. if (notifyObject.pressed) {
  72283. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72284. }
  72285. else {
  72286. (this._defaultModel.getChildren()[2]).position.y = 0;
  72287. }
  72288. }
  72289. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72290. return;
  72291. }
  72292. };
  72293. /**
  72294. * Base Url for the controller model.
  72295. */
  72296. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72297. /**
  72298. * File name for the controller model.
  72299. */
  72300. ViveController.MODEL_FILENAME = 'wand.babylon';
  72301. return ViveController;
  72302. }(BABYLON.WebVRController));
  72303. BABYLON.ViveController = ViveController;
  72304. })(BABYLON || (BABYLON = {}));
  72305. //# sourceMappingURL=babylon.viveController.js.map
  72306. var BABYLON;
  72307. (function (BABYLON) {
  72308. /**
  72309. * Generic Controller
  72310. */
  72311. var GenericController = /** @class */ (function (_super) {
  72312. __extends(GenericController, _super);
  72313. /**
  72314. * Creates a new GenericController from a gamepad
  72315. * @param vrGamepad the gamepad that the controller should be created from
  72316. */
  72317. function GenericController(vrGamepad) {
  72318. return _super.call(this, vrGamepad) || this;
  72319. }
  72320. /**
  72321. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72322. * @param scene scene in which to add meshes
  72323. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72324. */
  72325. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72326. var _this = this;
  72327. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72328. _this._defaultModel = newMeshes[1];
  72329. _this.attachToMesh(_this._defaultModel);
  72330. if (meshLoaded) {
  72331. meshLoaded(_this._defaultModel);
  72332. }
  72333. });
  72334. };
  72335. /**
  72336. * Called once for each button that changed state since the last frame
  72337. * @param buttonIdx Which button index changed
  72338. * @param state New state of the button
  72339. * @param changes Which properties on the state changed since last frame
  72340. */
  72341. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72342. console.log("Button id: " + buttonIdx + "state: ");
  72343. console.dir(state);
  72344. };
  72345. /**
  72346. * Base Url for the controller model.
  72347. */
  72348. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72349. /**
  72350. * File name for the controller model.
  72351. */
  72352. GenericController.MODEL_FILENAME = 'generic.babylon';
  72353. return GenericController;
  72354. }(BABYLON.WebVRController));
  72355. BABYLON.GenericController = GenericController;
  72356. })(BABYLON || (BABYLON = {}));
  72357. //# sourceMappingURL=babylon.genericController.js.map
  72358. var BABYLON;
  72359. (function (BABYLON) {
  72360. /**
  72361. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72362. */
  72363. var LoadedMeshInfo = /** @class */ (function () {
  72364. function LoadedMeshInfo() {
  72365. /**
  72366. * Map of the button meshes contained in the controller
  72367. */
  72368. this.buttonMeshes = {};
  72369. /**
  72370. * Map of the axis meshes contained in the controller
  72371. */
  72372. this.axisMeshes = {};
  72373. }
  72374. return LoadedMeshInfo;
  72375. }());
  72376. /**
  72377. * Defines the WindowsMotionController object that the state of the windows motion controller
  72378. */
  72379. var WindowsMotionController = /** @class */ (function (_super) {
  72380. __extends(WindowsMotionController, _super);
  72381. /**
  72382. * Creates a new WindowsMotionController from a gamepad
  72383. * @param vrGamepad the gamepad that the controller should be created from
  72384. */
  72385. function WindowsMotionController(vrGamepad) {
  72386. var _this = _super.call(this, vrGamepad) || this;
  72387. _this._mapping = {
  72388. // Semantic button names
  72389. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72390. // A mapping of the button name to glTF model node name
  72391. // that should be transformed by button value.
  72392. buttonMeshNames: {
  72393. 'trigger': 'SELECT',
  72394. 'menu': 'MENU',
  72395. 'grip': 'GRASP',
  72396. 'thumbstick': 'THUMBSTICK_PRESS',
  72397. 'trackpad': 'TOUCHPAD_PRESS'
  72398. },
  72399. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72400. buttonObservableNames: {
  72401. 'trigger': 'onTriggerStateChangedObservable',
  72402. 'menu': 'onSecondaryButtonStateChangedObservable',
  72403. 'grip': 'onMainButtonStateChangedObservable',
  72404. 'thumbstick': 'onPadStateChangedObservable',
  72405. 'trackpad': 'onTrackpadChangedObservable'
  72406. },
  72407. // A mapping of the axis name to glTF model node name
  72408. // that should be transformed by axis value.
  72409. // This array mirrors the browserGamepad.axes array, such that
  72410. // the mesh corresponding to axis 0 is in this array index 0.
  72411. axisMeshNames: [
  72412. 'THUMBSTICK_X',
  72413. 'THUMBSTICK_Y',
  72414. 'TOUCHPAD_TOUCH_X',
  72415. 'TOUCHPAD_TOUCH_Y'
  72416. ],
  72417. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72418. };
  72419. /**
  72420. * Fired when the trackpad on this controller is clicked
  72421. */
  72422. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72423. /**
  72424. * Fired when the trackpad on this controller is modified
  72425. */
  72426. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72427. /**
  72428. * The current x and y values of this controller's trackpad
  72429. */
  72430. _this.trackpad = { x: 0, y: 0 };
  72431. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72432. _this._loadedMeshInfo = null;
  72433. return _this;
  72434. }
  72435. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72436. /**
  72437. * Fired when the trigger on this controller is modified
  72438. */
  72439. get: function () {
  72440. return this.onTriggerStateChangedObservable;
  72441. },
  72442. enumerable: true,
  72443. configurable: true
  72444. });
  72445. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72446. /**
  72447. * Fired when the menu button on this controller is modified
  72448. */
  72449. get: function () {
  72450. return this.onSecondaryButtonStateChangedObservable;
  72451. },
  72452. enumerable: true,
  72453. configurable: true
  72454. });
  72455. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72456. /**
  72457. * Fired when the grip button on this controller is modified
  72458. */
  72459. get: function () {
  72460. return this.onMainButtonStateChangedObservable;
  72461. },
  72462. enumerable: true,
  72463. configurable: true
  72464. });
  72465. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72466. /**
  72467. * Fired when the thumbstick button on this controller is modified
  72468. */
  72469. get: function () {
  72470. return this.onPadStateChangedObservable;
  72471. },
  72472. enumerable: true,
  72473. configurable: true
  72474. });
  72475. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72476. /**
  72477. * Fired when the touchpad button on this controller is modified
  72478. */
  72479. get: function () {
  72480. return this.onTrackpadChangedObservable;
  72481. },
  72482. enumerable: true,
  72483. configurable: true
  72484. });
  72485. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72486. /**
  72487. * Fired when the touchpad values on this controller are modified
  72488. */
  72489. get: function () {
  72490. return this.onTrackpadValuesChangedObservable;
  72491. },
  72492. enumerable: true,
  72493. configurable: true
  72494. });
  72495. /**
  72496. * Called once per frame by the engine.
  72497. */
  72498. WindowsMotionController.prototype.update = function () {
  72499. _super.prototype.update.call(this);
  72500. if (this.browserGamepad.axes) {
  72501. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72502. this.trackpad.x = this.browserGamepad["axes"][2];
  72503. this.trackpad.y = this.browserGamepad["axes"][3];
  72504. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72505. }
  72506. // Only need to animate axes if there is a loaded mesh
  72507. if (this._loadedMeshInfo) {
  72508. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72509. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72510. }
  72511. }
  72512. }
  72513. };
  72514. /**
  72515. * Called once for each button that changed state since the last frame
  72516. * @param buttonIdx Which button index changed
  72517. * @param state New state of the button
  72518. * @param changes Which properties on the state changed since last frame
  72519. */
  72520. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72521. var buttonName = this._mapping.buttons[buttonIdx];
  72522. if (!buttonName) {
  72523. return;
  72524. }
  72525. // Only emit events for buttons that we know how to map from index to name
  72526. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72527. if (observable) {
  72528. observable.notifyObservers(state);
  72529. }
  72530. this._lerpButtonTransform(buttonName, state.value);
  72531. };
  72532. /**
  72533. * Moves the buttons on the controller mesh based on their current state
  72534. * @param buttonName the name of the button to move
  72535. * @param buttonValue the value of the button which determines the buttons new position
  72536. */
  72537. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72538. // If there is no loaded mesh, there is nothing to transform.
  72539. if (!this._loadedMeshInfo) {
  72540. return;
  72541. }
  72542. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72543. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72544. return;
  72545. }
  72546. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72547. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72548. };
  72549. /**
  72550. * Moves the axis on the controller mesh based on its current state
  72551. * @param axis the index of the axis
  72552. * @param axisValue the value of the axis which determines the meshes new position
  72553. * @hidden
  72554. */
  72555. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72556. if (!this._loadedMeshInfo) {
  72557. return;
  72558. }
  72559. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72560. if (!meshInfo) {
  72561. return;
  72562. }
  72563. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72564. return;
  72565. }
  72566. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72567. var lerpValue = axisValue * 0.5 + 0.5;
  72568. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72569. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72570. };
  72571. /**
  72572. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72573. * @param scene scene in which to add meshes
  72574. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72575. */
  72576. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72577. var _this = this;
  72578. if (forceDefault === void 0) { forceDefault = false; }
  72579. var path;
  72580. var filename;
  72581. // Checking if GLB loader is present
  72582. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72583. // Determine the device specific folder based on the ID suffix
  72584. var device = 'default';
  72585. if (this.id && !forceDefault) {
  72586. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72587. device = ((match && match[0]) || device);
  72588. }
  72589. // Hand
  72590. if (this.hand === 'left') {
  72591. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72592. }
  72593. else { // Right is the default if no hand is specified
  72594. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72595. }
  72596. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72597. }
  72598. else {
  72599. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72600. path = BABYLON.GenericController.MODEL_BASE_URL;
  72601. filename = BABYLON.GenericController.MODEL_FILENAME;
  72602. }
  72603. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72604. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72605. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72606. if (!_this._loadedMeshInfo) {
  72607. return;
  72608. }
  72609. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72610. _this.attachToMesh(_this._defaultModel);
  72611. if (meshLoaded) {
  72612. meshLoaded(_this._defaultModel);
  72613. }
  72614. }, null, function (scene, message) {
  72615. BABYLON.Tools.Log(message);
  72616. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72617. if (!forceDefault) {
  72618. _this.initControllerMesh(scene, meshLoaded, true);
  72619. }
  72620. });
  72621. };
  72622. /**
  72623. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72624. * can be transformed by button presses and axes values, based on this._mapping.
  72625. *
  72626. * @param scene scene in which the meshes exist
  72627. * @param meshes list of meshes that make up the controller model to process
  72628. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72629. */
  72630. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72631. var loadedMeshInfo = null;
  72632. // Create a new mesh to contain the glTF hierarchy
  72633. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72634. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72635. var childMesh = null;
  72636. for (var i = 0; i < meshes.length; i++) {
  72637. var mesh = meshes[i];
  72638. if (!mesh.parent) {
  72639. // Exclude controller meshes from picking results
  72640. mesh.isPickable = false;
  72641. // Handle root node, attach to the new parentMesh
  72642. childMesh = mesh;
  72643. break;
  72644. }
  72645. }
  72646. if (childMesh) {
  72647. childMesh.setParent(parentMesh);
  72648. // Create our mesh info. Note that this method will always return non-null.
  72649. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72650. }
  72651. else {
  72652. BABYLON.Tools.Warn('Could not find root node in model file.');
  72653. }
  72654. return loadedMeshInfo;
  72655. };
  72656. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72657. var loadedMeshInfo = new LoadedMeshInfo();
  72658. var i;
  72659. loadedMeshInfo.rootNode = rootNode;
  72660. // Reset the caches
  72661. loadedMeshInfo.buttonMeshes = {};
  72662. loadedMeshInfo.axisMeshes = {};
  72663. // Button Meshes
  72664. for (i = 0; i < this._mapping.buttons.length; i++) {
  72665. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72666. if (!buttonMeshName) {
  72667. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72668. continue;
  72669. }
  72670. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72671. if (!buttonMesh) {
  72672. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72673. continue;
  72674. }
  72675. var buttonMeshInfo = {
  72676. index: i,
  72677. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72678. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72679. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72680. };
  72681. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72682. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72683. }
  72684. else {
  72685. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72686. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72687. '(VALUE: ' + !!buttonMeshInfo.value +
  72688. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72689. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72690. ')');
  72691. }
  72692. }
  72693. // Axis Meshes
  72694. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72695. var axisMeshName = this._mapping.axisMeshNames[i];
  72696. if (!axisMeshName) {
  72697. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72698. continue;
  72699. }
  72700. var axisMesh = getChildByName(rootNode, axisMeshName);
  72701. if (!axisMesh) {
  72702. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72703. continue;
  72704. }
  72705. var axisMeshInfo = {
  72706. index: i,
  72707. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72708. min: getImmediateChildByName(axisMesh, 'MIN'),
  72709. max: getImmediateChildByName(axisMesh, 'MAX')
  72710. };
  72711. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72712. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72713. }
  72714. else {
  72715. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72716. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72717. '(VALUE: ' + !!axisMeshInfo.value +
  72718. ', MIN: ' + !!axisMeshInfo.min +
  72719. ', MAX:' + !!axisMeshInfo.max +
  72720. ')');
  72721. }
  72722. }
  72723. // Pointing Ray
  72724. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72725. if (!loadedMeshInfo.pointingPoseNode) {
  72726. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72727. }
  72728. return loadedMeshInfo;
  72729. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72730. function getChildByName(node, name) {
  72731. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72732. }
  72733. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72734. function getImmediateChildByName(node, name) {
  72735. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72736. }
  72737. };
  72738. /**
  72739. * Gets the ray of the controller in the direction the controller is pointing
  72740. * @param length the length the resulting ray should be
  72741. * @returns a ray in the direction the controller is pointing
  72742. */
  72743. WindowsMotionController.prototype.getForwardRay = function (length) {
  72744. if (length === void 0) { length = 100; }
  72745. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72746. return _super.prototype.getForwardRay.call(this, length);
  72747. }
  72748. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72749. var origin = m.getTranslation();
  72750. var forward = new BABYLON.Vector3(0, 0, -1);
  72751. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72752. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72753. return new BABYLON.Ray(origin, direction, length);
  72754. };
  72755. /**
  72756. * Disposes of the controller
  72757. */
  72758. WindowsMotionController.prototype.dispose = function () {
  72759. _super.prototype.dispose.call(this);
  72760. this.onTrackpadChangedObservable.clear();
  72761. };
  72762. /**
  72763. * The base url used to load the left and right controller models
  72764. */
  72765. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72766. /**
  72767. * The name of the left controller model file
  72768. */
  72769. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72770. /**
  72771. * The name of the right controller model file
  72772. */
  72773. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72774. /**
  72775. * The controller name prefix for this controller type
  72776. */
  72777. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72778. /**
  72779. * The controller id pattern for this controller type
  72780. */
  72781. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72782. return WindowsMotionController;
  72783. }(BABYLON.WebVRController));
  72784. BABYLON.WindowsMotionController = WindowsMotionController;
  72785. })(BABYLON || (BABYLON = {}));
  72786. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72787. var BABYLON;
  72788. (function (BABYLON) {
  72789. /**
  72790. * Gear VR Controller
  72791. */
  72792. var GearVRController = /** @class */ (function (_super) {
  72793. __extends(GearVRController, _super);
  72794. /**
  72795. * Creates a new GearVRController from a gamepad
  72796. * @param vrGamepad the gamepad that the controller should be created from
  72797. */
  72798. function GearVRController(vrGamepad) {
  72799. var _this = _super.call(this, vrGamepad) || this;
  72800. _this._buttonIndexToObservableNameMap = [
  72801. 'onTrackpadChangedObservable',
  72802. 'onTriggerStateChangedObservable' // Trigger
  72803. ];
  72804. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72805. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72806. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72807. return _this;
  72808. }
  72809. /**
  72810. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72811. * @param scene scene in which to add meshes
  72812. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72813. */
  72814. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72815. var _this = this;
  72816. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72817. _this._defaultModel = newMeshes[1];
  72818. _this.attachToMesh(_this._defaultModel);
  72819. if (meshLoaded) {
  72820. meshLoaded(_this._defaultModel);
  72821. }
  72822. });
  72823. };
  72824. /**
  72825. * Called once for each button that changed state since the last frame
  72826. * @param buttonIdx Which button index changed
  72827. * @param state New state of the button
  72828. * @param changes Which properties on the state changed since last frame
  72829. */
  72830. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72831. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72832. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72833. // Only emit events for buttons that we know how to map from index to observable
  72834. var observable = this[observableName];
  72835. if (observable) {
  72836. observable.notifyObservers(state);
  72837. }
  72838. }
  72839. };
  72840. /**
  72841. * Base Url for the controller model.
  72842. */
  72843. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72844. /**
  72845. * File name for the controller model.
  72846. */
  72847. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72848. /**
  72849. * Gamepad Id prefix used to identify this controller.
  72850. */
  72851. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72852. return GearVRController;
  72853. }(BABYLON.WebVRController));
  72854. BABYLON.GearVRController = GearVRController;
  72855. })(BABYLON || (BABYLON = {}));
  72856. //# sourceMappingURL=babylon.gearVRController.js.map
  72857. var BABYLON;
  72858. (function (BABYLON) {
  72859. /**
  72860. * Google Daydream controller
  72861. */
  72862. var DaydreamController = /** @class */ (function (_super) {
  72863. __extends(DaydreamController, _super);
  72864. /**
  72865. * Creates a new DaydreamController from a gamepad
  72866. * @param vrGamepad the gamepad that the controller should be created from
  72867. */
  72868. function DaydreamController(vrGamepad) {
  72869. var _this = _super.call(this, vrGamepad) || this;
  72870. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72871. return _this;
  72872. }
  72873. /**
  72874. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72875. * @param scene scene in which to add meshes
  72876. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72877. */
  72878. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72879. var _this = this;
  72880. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72881. _this._defaultModel = newMeshes[1];
  72882. _this.attachToMesh(_this._defaultModel);
  72883. if (meshLoaded) {
  72884. meshLoaded(_this._defaultModel);
  72885. }
  72886. });
  72887. };
  72888. /**
  72889. * Called once for each button that changed state since the last frame
  72890. * @param buttonIdx Which button index changed
  72891. * @param state New state of the button
  72892. * @param changes Which properties on the state changed since last frame
  72893. */
  72894. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72895. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72896. if (buttonIdx === 0) {
  72897. var observable = this.onTriggerStateChangedObservable;
  72898. if (observable) {
  72899. observable.notifyObservers(state);
  72900. }
  72901. }
  72902. else {
  72903. // If the app or home buttons are ever made available
  72904. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72905. }
  72906. };
  72907. /**
  72908. * Base Url for the controller model.
  72909. */
  72910. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72911. /**
  72912. * File name for the controller model.
  72913. */
  72914. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72915. /**
  72916. * Gamepad Id prefix used to identify Daydream Controller.
  72917. */
  72918. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72919. return DaydreamController;
  72920. }(BABYLON.WebVRController));
  72921. BABYLON.DaydreamController = DaydreamController;
  72922. })(BABYLON || (BABYLON = {}));
  72923. //# sourceMappingURL=babylon.daydreamController.js.map
  72924. var BABYLON;
  72925. (function (BABYLON) {
  72926. var FollowCamera = /** @class */ (function (_super) {
  72927. __extends(FollowCamera, _super);
  72928. function FollowCamera(name, position, scene, lockedTarget) {
  72929. if (lockedTarget === void 0) { lockedTarget = null; }
  72930. var _this = _super.call(this, name, position, scene) || this;
  72931. _this.radius = 12;
  72932. _this.rotationOffset = 0;
  72933. _this.heightOffset = 4;
  72934. _this.cameraAcceleration = 0.05;
  72935. _this.maxCameraSpeed = 20;
  72936. _this.lockedTarget = lockedTarget;
  72937. return _this;
  72938. }
  72939. FollowCamera.prototype.getRadians = function (degrees) {
  72940. return degrees * Math.PI / 180;
  72941. };
  72942. FollowCamera.prototype.follow = function (cameraTarget) {
  72943. if (!cameraTarget)
  72944. return;
  72945. var yRotation;
  72946. if (cameraTarget.rotationQuaternion) {
  72947. var rotMatrix = new BABYLON.Matrix();
  72948. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72949. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72950. }
  72951. else {
  72952. yRotation = cameraTarget.rotation.y;
  72953. }
  72954. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72955. var targetPosition = cameraTarget.getAbsolutePosition();
  72956. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72957. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72958. var dx = targetX - this.position.x;
  72959. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72960. var dz = (targetZ) - this.position.z;
  72961. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72962. var vy = dy * this.cameraAcceleration;
  72963. var vz = dz * this.cameraAcceleration * 2;
  72964. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72965. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72966. }
  72967. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72968. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72969. }
  72970. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72971. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72972. }
  72973. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72974. this.setTarget(targetPosition);
  72975. };
  72976. FollowCamera.prototype._checkInputs = function () {
  72977. _super.prototype._checkInputs.call(this);
  72978. if (this.lockedTarget) {
  72979. this.follow(this.lockedTarget);
  72980. }
  72981. };
  72982. FollowCamera.prototype.getClassName = function () {
  72983. return "FollowCamera";
  72984. };
  72985. __decorate([
  72986. BABYLON.serialize()
  72987. ], FollowCamera.prototype, "radius", void 0);
  72988. __decorate([
  72989. BABYLON.serialize()
  72990. ], FollowCamera.prototype, "rotationOffset", void 0);
  72991. __decorate([
  72992. BABYLON.serialize()
  72993. ], FollowCamera.prototype, "heightOffset", void 0);
  72994. __decorate([
  72995. BABYLON.serialize()
  72996. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72997. __decorate([
  72998. BABYLON.serialize()
  72999. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73000. __decorate([
  73001. BABYLON.serializeAsMeshReference("lockedTargetId")
  73002. ], FollowCamera.prototype, "lockedTarget", void 0);
  73003. return FollowCamera;
  73004. }(BABYLON.TargetCamera));
  73005. BABYLON.FollowCamera = FollowCamera;
  73006. var ArcFollowCamera = /** @class */ (function (_super) {
  73007. __extends(ArcFollowCamera, _super);
  73008. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73009. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73010. _this.alpha = alpha;
  73011. _this.beta = beta;
  73012. _this.radius = radius;
  73013. _this.target = target;
  73014. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73015. _this.follow();
  73016. return _this;
  73017. }
  73018. ArcFollowCamera.prototype.follow = function () {
  73019. if (!this.target) {
  73020. return;
  73021. }
  73022. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73023. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73024. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73025. var targetPosition = this.target.getAbsolutePosition();
  73026. this.position = targetPosition.add(this._cartesianCoordinates);
  73027. this.setTarget(targetPosition);
  73028. };
  73029. ArcFollowCamera.prototype._checkInputs = function () {
  73030. _super.prototype._checkInputs.call(this);
  73031. this.follow();
  73032. };
  73033. ArcFollowCamera.prototype.getClassName = function () {
  73034. return "ArcFollowCamera";
  73035. };
  73036. return ArcFollowCamera;
  73037. }(BABYLON.TargetCamera));
  73038. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73039. })(BABYLON || (BABYLON = {}));
  73040. //# sourceMappingURL=babylon.followCamera.js.map
  73041. var BABYLON;
  73042. (function (BABYLON) {
  73043. // We're mainly based on the logic defined into the FreeCamera code
  73044. var UniversalCamera = /** @class */ (function (_super) {
  73045. __extends(UniversalCamera, _super);
  73046. //-- end properties for backward compatibility for inputs
  73047. function UniversalCamera(name, position, scene) {
  73048. var _this = _super.call(this, name, position, scene) || this;
  73049. _this.inputs.addGamepad();
  73050. return _this;
  73051. }
  73052. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73053. //-- Begin properties for backward compatibility for inputs
  73054. get: function () {
  73055. var gamepad = this.inputs.attached["gamepad"];
  73056. if (gamepad)
  73057. return gamepad.gamepadAngularSensibility;
  73058. return 0;
  73059. },
  73060. set: function (value) {
  73061. var gamepad = this.inputs.attached["gamepad"];
  73062. if (gamepad)
  73063. gamepad.gamepadAngularSensibility = value;
  73064. },
  73065. enumerable: true,
  73066. configurable: true
  73067. });
  73068. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73069. get: function () {
  73070. var gamepad = this.inputs.attached["gamepad"];
  73071. if (gamepad)
  73072. return gamepad.gamepadMoveSensibility;
  73073. return 0;
  73074. },
  73075. set: function (value) {
  73076. var gamepad = this.inputs.attached["gamepad"];
  73077. if (gamepad)
  73078. gamepad.gamepadMoveSensibility = value;
  73079. },
  73080. enumerable: true,
  73081. configurable: true
  73082. });
  73083. UniversalCamera.prototype.getClassName = function () {
  73084. return "UniversalCamera";
  73085. };
  73086. return UniversalCamera;
  73087. }(BABYLON.TouchCamera));
  73088. BABYLON.UniversalCamera = UniversalCamera;
  73089. })(BABYLON || (BABYLON = {}));
  73090. //# sourceMappingURL=babylon.universalCamera.js.map
  73091. var BABYLON;
  73092. (function (BABYLON) {
  73093. // We're mainly based on the logic defined into the FreeCamera code
  73094. var GamepadCamera = /** @class */ (function (_super) {
  73095. __extends(GamepadCamera, _super);
  73096. //-- end properties for backward compatibility for inputs
  73097. function GamepadCamera(name, position, scene) {
  73098. return _super.call(this, name, position, scene) || this;
  73099. }
  73100. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73101. //-- Begin properties for backward compatibility for inputs
  73102. get: function () {
  73103. var gamepad = this.inputs.attached["gamepad"];
  73104. if (gamepad)
  73105. return gamepad.gamepadAngularSensibility;
  73106. return 0;
  73107. },
  73108. set: function (value) {
  73109. var gamepad = this.inputs.attached["gamepad"];
  73110. if (gamepad)
  73111. gamepad.gamepadAngularSensibility = value;
  73112. },
  73113. enumerable: true,
  73114. configurable: true
  73115. });
  73116. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73117. get: function () {
  73118. var gamepad = this.inputs.attached["gamepad"];
  73119. if (gamepad)
  73120. return gamepad.gamepadMoveSensibility;
  73121. return 0;
  73122. },
  73123. set: function (value) {
  73124. var gamepad = this.inputs.attached["gamepad"];
  73125. if (gamepad)
  73126. gamepad.gamepadMoveSensibility = value;
  73127. },
  73128. enumerable: true,
  73129. configurable: true
  73130. });
  73131. GamepadCamera.prototype.getClassName = function () {
  73132. return "GamepadCamera";
  73133. };
  73134. return GamepadCamera;
  73135. }(BABYLON.UniversalCamera));
  73136. BABYLON.GamepadCamera = GamepadCamera;
  73137. })(BABYLON || (BABYLON = {}));
  73138. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73139. var BABYLON;
  73140. (function (BABYLON) {
  73141. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73142. function PostProcessRenderPipelineManager() {
  73143. this._renderPipelines = {};
  73144. }
  73145. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73146. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73147. };
  73148. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73149. if (unique === void 0) { unique = false; }
  73150. var renderPipeline = this._renderPipelines[renderPipelineName];
  73151. if (!renderPipeline) {
  73152. return;
  73153. }
  73154. renderPipeline._attachCameras(cameras, unique);
  73155. };
  73156. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73157. var renderPipeline = this._renderPipelines[renderPipelineName];
  73158. if (!renderPipeline) {
  73159. return;
  73160. }
  73161. renderPipeline._detachCameras(cameras);
  73162. };
  73163. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73164. var renderPipeline = this._renderPipelines[renderPipelineName];
  73165. if (!renderPipeline) {
  73166. return;
  73167. }
  73168. renderPipeline._enableEffect(renderEffectName, cameras);
  73169. };
  73170. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73171. var renderPipeline = this._renderPipelines[renderPipelineName];
  73172. if (!renderPipeline) {
  73173. return;
  73174. }
  73175. renderPipeline._disableEffect(renderEffectName, cameras);
  73176. };
  73177. PostProcessRenderPipelineManager.prototype.update = function () {
  73178. for (var renderPipelineName in this._renderPipelines) {
  73179. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73180. var pipeline = this._renderPipelines[renderPipelineName];
  73181. if (!pipeline.isSupported) {
  73182. pipeline.dispose();
  73183. delete this._renderPipelines[renderPipelineName];
  73184. }
  73185. else {
  73186. pipeline._update();
  73187. }
  73188. }
  73189. }
  73190. };
  73191. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73192. for (var renderPipelineName in this._renderPipelines) {
  73193. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73194. var pipeline = this._renderPipelines[renderPipelineName];
  73195. pipeline._rebuild();
  73196. }
  73197. }
  73198. };
  73199. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73200. for (var renderPipelineName in this._renderPipelines) {
  73201. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73202. var pipeline = this._renderPipelines[renderPipelineName];
  73203. pipeline.dispose();
  73204. }
  73205. }
  73206. };
  73207. return PostProcessRenderPipelineManager;
  73208. }());
  73209. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73210. })(BABYLON || (BABYLON = {}));
  73211. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73212. var BABYLON;
  73213. (function (BABYLON) {
  73214. /**
  73215. * This represents a set of one or more post processes in Babylon.
  73216. * A post process can be used to apply a shader to a texture after it is rendered.
  73217. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73218. */
  73219. var PostProcessRenderEffect = /** @class */ (function () {
  73220. /**
  73221. * Instantiates a post process render effect.
  73222. * A post process can be used to apply a shader to a texture after it is rendered.
  73223. * @param engine The engine the effect is tied to
  73224. * @param name The name of the effect
  73225. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73226. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73227. */
  73228. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73229. this._name = name;
  73230. this._singleInstance = singleInstance || true;
  73231. this._getPostProcesses = getPostProcesses;
  73232. this._cameras = {};
  73233. this._indicesForCamera = {};
  73234. this._postProcesses = {};
  73235. }
  73236. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73237. /**
  73238. * Checks if all the post processes in the effect are supported.
  73239. */
  73240. get: function () {
  73241. for (var index in this._postProcesses) {
  73242. if (this._postProcesses.hasOwnProperty(index)) {
  73243. var pps = this._postProcesses[index];
  73244. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73245. if (!pps[ppIndex].isSupported) {
  73246. return false;
  73247. }
  73248. }
  73249. }
  73250. }
  73251. return true;
  73252. },
  73253. enumerable: true,
  73254. configurable: true
  73255. });
  73256. /**
  73257. * Updates the current state of the effect
  73258. */
  73259. PostProcessRenderEffect.prototype._update = function () {
  73260. };
  73261. /**
  73262. * Attaches the effect on cameras
  73263. * @param cameras The camera to attach to.
  73264. */
  73265. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73266. var _this = this;
  73267. var cameraKey;
  73268. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73269. if (!cams) {
  73270. return;
  73271. }
  73272. for (var i = 0; i < cams.length; i++) {
  73273. var camera = cams[i];
  73274. var cameraName = camera.name;
  73275. if (this._singleInstance) {
  73276. cameraKey = 0;
  73277. }
  73278. else {
  73279. cameraKey = cameraName;
  73280. }
  73281. if (!this._postProcesses[cameraKey]) {
  73282. var postProcess = this._getPostProcesses();
  73283. if (postProcess) {
  73284. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73285. }
  73286. }
  73287. if (!this._indicesForCamera[cameraName]) {
  73288. this._indicesForCamera[cameraName] = [];
  73289. }
  73290. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73291. var index = camera.attachPostProcess(postProcess);
  73292. _this._indicesForCamera[cameraName].push(index);
  73293. });
  73294. if (!this._cameras[cameraName]) {
  73295. this._cameras[cameraName] = camera;
  73296. }
  73297. }
  73298. };
  73299. /**
  73300. * Detatches the effect on cameras
  73301. * @param cameras The camera to detatch from.
  73302. */
  73303. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73304. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73305. if (!cams) {
  73306. return;
  73307. }
  73308. for (var i = 0; i < cams.length; i++) {
  73309. var camera = cams[i];
  73310. var cameraName = camera.name;
  73311. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73312. camera.detachPostProcess(postProcess);
  73313. });
  73314. if (this._cameras[cameraName]) {
  73315. //this._indicesForCamera.splice(index, 1);
  73316. this._cameras[cameraName] = null;
  73317. }
  73318. }
  73319. };
  73320. /**
  73321. * Enables the effect on given cameras
  73322. * @param cameras The camera to enable.
  73323. */
  73324. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73325. var _this = this;
  73326. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73327. if (!cams) {
  73328. return;
  73329. }
  73330. for (var i = 0; i < cams.length; i++) {
  73331. var camera = cams[i];
  73332. var cameraName = camera.name;
  73333. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73334. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73335. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73336. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73337. });
  73338. }
  73339. }
  73340. }
  73341. };
  73342. /**
  73343. * Disables the effect on the given cameras
  73344. * @param cameras The camera to disable.
  73345. */
  73346. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73347. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73348. if (!cams) {
  73349. return;
  73350. }
  73351. for (var i = 0; i < cams.length; i++) {
  73352. var camera = cams[i];
  73353. var cameraName = camera.name;
  73354. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73355. camera.detachPostProcess(postProcess);
  73356. });
  73357. }
  73358. };
  73359. /**
  73360. * Gets a list of the post processes contained in the effect.
  73361. * @param camera The camera to get the post processes on.
  73362. * @returns The list of the post processes in the effect.
  73363. */
  73364. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73365. if (this._singleInstance) {
  73366. return this._postProcesses[0];
  73367. }
  73368. else {
  73369. if (!camera) {
  73370. return null;
  73371. }
  73372. return this._postProcesses[camera.name];
  73373. }
  73374. };
  73375. return PostProcessRenderEffect;
  73376. }());
  73377. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73378. })(BABYLON || (BABYLON = {}));
  73379. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73380. var BABYLON;
  73381. (function (BABYLON) {
  73382. var PostProcessRenderPipeline = /** @class */ (function () {
  73383. function PostProcessRenderPipeline(engine, name) {
  73384. this.engine = engine;
  73385. this._name = name;
  73386. this._renderEffects = {};
  73387. this._renderEffectsForIsolatedPass = new Array();
  73388. this._cameras = [];
  73389. }
  73390. PostProcessRenderPipeline.prototype.getClassName = function () {
  73391. return "PostProcessRenderPipeline";
  73392. };
  73393. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73394. get: function () {
  73395. for (var renderEffectName in this._renderEffects) {
  73396. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73397. if (!this._renderEffects[renderEffectName].isSupported) {
  73398. return false;
  73399. }
  73400. }
  73401. }
  73402. return true;
  73403. },
  73404. enumerable: true,
  73405. configurable: true
  73406. });
  73407. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73408. this._renderEffects[renderEffect._name] = renderEffect;
  73409. };
  73410. // private
  73411. PostProcessRenderPipeline.prototype._rebuild = function () {
  73412. };
  73413. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73414. var renderEffects = this._renderEffects[renderEffectName];
  73415. if (!renderEffects) {
  73416. return;
  73417. }
  73418. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73419. };
  73420. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73421. var renderEffects = this._renderEffects[renderEffectName];
  73422. if (!renderEffects) {
  73423. return;
  73424. }
  73425. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73426. };
  73427. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73428. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73429. if (!cams) {
  73430. return;
  73431. }
  73432. var indicesToDelete = [];
  73433. var i;
  73434. for (i = 0; i < cams.length; i++) {
  73435. var camera = cams[i];
  73436. var cameraName = camera.name;
  73437. if (this._cameras.indexOf(camera) === -1) {
  73438. this._cameras[cameraName] = camera;
  73439. }
  73440. else if (unique) {
  73441. indicesToDelete.push(i);
  73442. }
  73443. }
  73444. for (i = 0; i < indicesToDelete.length; i++) {
  73445. cameras.splice(indicesToDelete[i], 1);
  73446. }
  73447. for (var renderEffectName in this._renderEffects) {
  73448. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73449. this._renderEffects[renderEffectName]._attachCameras(cams);
  73450. }
  73451. }
  73452. };
  73453. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73454. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73455. if (!cams) {
  73456. return;
  73457. }
  73458. for (var renderEffectName in this._renderEffects) {
  73459. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73460. this._renderEffects[renderEffectName]._detachCameras(cams);
  73461. }
  73462. }
  73463. for (var i = 0; i < cams.length; i++) {
  73464. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73465. }
  73466. };
  73467. PostProcessRenderPipeline.prototype._update = function () {
  73468. for (var renderEffectName in this._renderEffects) {
  73469. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73470. this._renderEffects[renderEffectName]._update();
  73471. }
  73472. }
  73473. for (var i = 0; i < this._cameras.length; i++) {
  73474. var cameraName = this._cameras[i].name;
  73475. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73476. this._renderEffectsForIsolatedPass[cameraName]._update();
  73477. }
  73478. }
  73479. };
  73480. PostProcessRenderPipeline.prototype._reset = function () {
  73481. this._renderEffects = {};
  73482. this._renderEffectsForIsolatedPass = new Array();
  73483. };
  73484. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73485. // 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)
  73486. var effectKeys = Object.keys(this._renderEffects);
  73487. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73488. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73489. if (postProcesses) {
  73490. postProcesses[0].samples = sampleCount;
  73491. return true;
  73492. }
  73493. }
  73494. return false;
  73495. };
  73496. PostProcessRenderPipeline.prototype.dispose = function () {
  73497. // Must be implemented by children
  73498. };
  73499. __decorate([
  73500. BABYLON.serialize()
  73501. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73502. return PostProcessRenderPipeline;
  73503. }());
  73504. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73505. })(BABYLON || (BABYLON = {}));
  73506. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73507. var BABYLON;
  73508. (function (BABYLON) {
  73509. /**
  73510. * This represents a depth renderer in Babylon.
  73511. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73512. */
  73513. var DepthRenderer = /** @class */ (function () {
  73514. /**
  73515. * Instantiates a depth renderer
  73516. * @param scene The scene the renderer belongs to
  73517. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73518. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73519. */
  73520. function DepthRenderer(scene, type, camera) {
  73521. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73522. if (camera === void 0) { camera = null; }
  73523. var _this = this;
  73524. this._scene = scene;
  73525. this._camera = camera;
  73526. var engine = scene.getEngine();
  73527. // Render target
  73528. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73529. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73530. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73531. this._depthMap.refreshRate = 1;
  73532. this._depthMap.renderParticles = false;
  73533. this._depthMap.renderList = null;
  73534. // Camera to get depth map from to support multiple concurrent cameras
  73535. this._depthMap.activeCamera = this._camera;
  73536. this._depthMap.ignoreCameraViewport = true;
  73537. this._depthMap.useCameraPostProcesses = false;
  73538. // set default depth value to 1.0 (far away)
  73539. this._depthMap.onClearObservable.add(function (engine) {
  73540. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73541. });
  73542. // Custom render function
  73543. var renderSubMesh = function (subMesh) {
  73544. var mesh = subMesh.getRenderingMesh();
  73545. var scene = _this._scene;
  73546. var engine = scene.getEngine();
  73547. var material = subMesh.getMaterial();
  73548. if (!material) {
  73549. return;
  73550. }
  73551. // Culling and reverse (right handed system)
  73552. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73553. // Managing instances
  73554. var batch = mesh._getInstancesRenderList(subMesh._id);
  73555. if (batch.mustReturn) {
  73556. return;
  73557. }
  73558. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73559. var camera = _this._camera || scene.activeCamera;
  73560. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73561. engine.enableEffect(_this._effect);
  73562. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73563. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73564. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73565. // Alpha test
  73566. if (material && material.needAlphaTesting()) {
  73567. var alphaTexture = material.getAlphaTestTexture();
  73568. if (alphaTexture) {
  73569. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73570. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73571. }
  73572. }
  73573. // Bones
  73574. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73575. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73576. }
  73577. // Draw
  73578. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73579. }
  73580. };
  73581. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73582. var index;
  73583. if (depthOnlySubMeshes.length) {
  73584. engine.setColorWrite(false);
  73585. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73586. renderSubMesh(depthOnlySubMeshes.data[index]);
  73587. }
  73588. engine.setColorWrite(true);
  73589. }
  73590. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73591. renderSubMesh(opaqueSubMeshes.data[index]);
  73592. }
  73593. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73594. renderSubMesh(alphaTestSubMeshes.data[index]);
  73595. }
  73596. };
  73597. }
  73598. /**
  73599. * Creates the depth rendering effect and checks if the effect is ready.
  73600. * @param subMesh The submesh to be used to render the depth map of
  73601. * @param useInstances If multiple world instances should be used
  73602. * @returns if the depth renderer is ready to render the depth map
  73603. */
  73604. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73605. var material = subMesh.getMaterial();
  73606. if (material.disableDepthWrite) {
  73607. return false;
  73608. }
  73609. var defines = [];
  73610. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73611. var mesh = subMesh.getMesh();
  73612. // Alpha test
  73613. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73614. defines.push("#define ALPHATEST");
  73615. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73616. attribs.push(BABYLON.VertexBuffer.UVKind);
  73617. defines.push("#define UV1");
  73618. }
  73619. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73620. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73621. defines.push("#define UV2");
  73622. }
  73623. }
  73624. // Bones
  73625. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73626. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73627. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73628. if (mesh.numBoneInfluencers > 4) {
  73629. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73630. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73631. }
  73632. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73633. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73634. }
  73635. else {
  73636. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73637. }
  73638. // Instances
  73639. if (useInstances) {
  73640. defines.push("#define INSTANCES");
  73641. attribs.push("world0");
  73642. attribs.push("world1");
  73643. attribs.push("world2");
  73644. attribs.push("world3");
  73645. }
  73646. // Get correct effect
  73647. var join = defines.join("\n");
  73648. if (this._cachedDefines !== join) {
  73649. this._cachedDefines = join;
  73650. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73651. }
  73652. return this._effect.isReady();
  73653. };
  73654. /**
  73655. * Gets the texture which the depth map will be written to.
  73656. * @returns The depth map texture
  73657. */
  73658. DepthRenderer.prototype.getDepthMap = function () {
  73659. return this._depthMap;
  73660. };
  73661. /**
  73662. * Disposes of the depth renderer.
  73663. */
  73664. DepthRenderer.prototype.dispose = function () {
  73665. this._depthMap.dispose();
  73666. };
  73667. return DepthRenderer;
  73668. }());
  73669. BABYLON.DepthRenderer = DepthRenderer;
  73670. })(BABYLON || (BABYLON = {}));
  73671. //# sourceMappingURL=babylon.depthRenderer.js.map
  73672. var BABYLON;
  73673. (function (BABYLON) {
  73674. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73675. __extends(SSAORenderingPipeline, _super);
  73676. /**
  73677. * @constructor
  73678. * @param {string} name - The rendering pipeline name
  73679. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73680. * @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 }
  73681. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73682. */
  73683. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73684. var _this = _super.call(this, scene.getEngine(), name) || this;
  73685. // Members
  73686. /**
  73687. * The PassPostProcess id in the pipeline that contains the original scene color
  73688. */
  73689. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73690. /**
  73691. * The SSAO PostProcess id in the pipeline
  73692. */
  73693. _this.SSAORenderEffect = "SSAORenderEffect";
  73694. /**
  73695. * The horizontal blur PostProcess id in the pipeline
  73696. */
  73697. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73698. /**
  73699. * The vertical blur PostProcess id in the pipeline
  73700. */
  73701. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73702. /**
  73703. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73704. */
  73705. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73706. /**
  73707. * The output strength of the SSAO post-process. Default value is 1.0.
  73708. */
  73709. _this.totalStrength = 1.0;
  73710. /**
  73711. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73712. */
  73713. _this.radius = 0.0001;
  73714. /**
  73715. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73716. * Must not be equal to fallOff and superior to fallOff.
  73717. * Default value is 0.975
  73718. */
  73719. _this.area = 0.0075;
  73720. /**
  73721. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73722. * Must not be equal to area and inferior to area.
  73723. * Default value is 0.0
  73724. */
  73725. _this.fallOff = 0.000001;
  73726. /**
  73727. * The base color of the SSAO post-process
  73728. * The final result is "base + ssao" between [0, 1]
  73729. */
  73730. _this.base = 0.5;
  73731. _this._firstUpdate = true;
  73732. _this._scene = scene;
  73733. // Set up assets
  73734. _this._createRandomTexture();
  73735. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73736. var ssaoRatio = ratio.ssaoRatio || ratio;
  73737. var combineRatio = ratio.combineRatio || ratio;
  73738. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73739. _this._createSSAOPostProcess(ssaoRatio);
  73740. _this._createBlurPostProcess(ssaoRatio);
  73741. _this._createSSAOCombinePostProcess(combineRatio);
  73742. // Set up pipeline
  73743. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73744. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73745. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73746. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73747. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73748. // Finish
  73749. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73750. if (cameras)
  73751. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73752. return _this;
  73753. }
  73754. // Public Methods
  73755. /**
  73756. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73757. */
  73758. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73759. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73760. for (var i = 0; i < this._scene.cameras.length; i++) {
  73761. var camera = this._scene.cameras[i];
  73762. this._originalColorPostProcess.dispose(camera);
  73763. this._ssaoPostProcess.dispose(camera);
  73764. this._blurHPostProcess.dispose(camera);
  73765. this._blurVPostProcess.dispose(camera);
  73766. this._ssaoCombinePostProcess.dispose(camera);
  73767. }
  73768. this._randomTexture.dispose();
  73769. if (disableDepthRender)
  73770. this._scene.disableDepthRenderer();
  73771. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73772. _super.prototype.dispose.call(this);
  73773. };
  73774. // Private Methods
  73775. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73776. var _this = this;
  73777. var size = 16;
  73778. 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);
  73779. 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);
  73780. this._blurHPostProcess.onActivateObservable.add(function () {
  73781. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73782. _this._blurHPostProcess.kernel = size * dw;
  73783. });
  73784. this._blurVPostProcess.onActivateObservable.add(function () {
  73785. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73786. _this._blurVPostProcess.kernel = size * dw;
  73787. });
  73788. };
  73789. SSAORenderingPipeline.prototype._rebuild = function () {
  73790. this._firstUpdate = true;
  73791. _super.prototype._rebuild.call(this);
  73792. };
  73793. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73794. var _this = this;
  73795. var numSamples = 16;
  73796. var sampleSphere = [
  73797. 0.5381, 0.1856, -0.4319,
  73798. 0.1379, 0.2486, 0.4430,
  73799. 0.3371, 0.5679, -0.0057,
  73800. -0.6999, -0.0451, -0.0019,
  73801. 0.0689, -0.1598, -0.8547,
  73802. 0.0560, 0.0069, -0.1843,
  73803. -0.0146, 0.1402, 0.0762,
  73804. 0.0100, -0.1924, -0.0344,
  73805. -0.3577, -0.5301, -0.4358,
  73806. -0.3169, 0.1063, 0.0158,
  73807. 0.0103, -0.5869, 0.0046,
  73808. -0.0897, -0.4940, 0.3287,
  73809. 0.7119, -0.0154, -0.0918,
  73810. -0.0533, 0.0596, -0.5411,
  73811. 0.0352, -0.0631, 0.5460,
  73812. -0.4776, 0.2847, -0.0271
  73813. ];
  73814. var samplesFactor = 1.0 / numSamples;
  73815. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73816. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73817. "area", "fallOff", "base", "range", "viewport"
  73818. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73819. this._ssaoPostProcess.onApply = function (effect) {
  73820. if (_this._firstUpdate) {
  73821. effect.setArray3("sampleSphere", sampleSphere);
  73822. effect.setFloat("samplesFactor", samplesFactor);
  73823. effect.setFloat("randTextureTiles", 4.0);
  73824. }
  73825. effect.setFloat("totalStrength", _this.totalStrength);
  73826. effect.setFloat("radius", _this.radius);
  73827. effect.setFloat("area", _this.area);
  73828. effect.setFloat("fallOff", _this.fallOff);
  73829. effect.setFloat("base", _this.base);
  73830. effect.setTexture("textureSampler", _this._depthTexture);
  73831. effect.setTexture("randomSampler", _this._randomTexture);
  73832. };
  73833. };
  73834. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73835. var _this = this;
  73836. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73837. this._ssaoCombinePostProcess.onApply = function (effect) {
  73838. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73839. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73840. };
  73841. };
  73842. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73843. var size = 512;
  73844. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73845. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73846. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73847. var context = this._randomTexture.getContext();
  73848. var rand = function (min, max) {
  73849. return Math.random() * (max - min) + min;
  73850. };
  73851. var randVector = BABYLON.Vector3.Zero();
  73852. for (var x = 0; x < size; x++) {
  73853. for (var y = 0; y < size; y++) {
  73854. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73855. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73856. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73857. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73858. context.fillRect(x, y, 1, 1);
  73859. }
  73860. }
  73861. this._randomTexture.update(false);
  73862. };
  73863. __decorate([
  73864. BABYLON.serialize()
  73865. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73866. __decorate([
  73867. BABYLON.serialize()
  73868. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73869. __decorate([
  73870. BABYLON.serialize()
  73871. ], SSAORenderingPipeline.prototype, "area", void 0);
  73872. __decorate([
  73873. BABYLON.serialize()
  73874. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73875. __decorate([
  73876. BABYLON.serialize()
  73877. ], SSAORenderingPipeline.prototype, "base", void 0);
  73878. return SSAORenderingPipeline;
  73879. }(BABYLON.PostProcessRenderPipeline));
  73880. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73881. })(BABYLON || (BABYLON = {}));
  73882. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73883. var BABYLON;
  73884. (function (BABYLON) {
  73885. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73886. __extends(SSAO2RenderingPipeline, _super);
  73887. /**
  73888. * @constructor
  73889. * @param {string} name - The rendering pipeline name
  73890. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73891. * @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 }
  73892. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73893. */
  73894. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73895. var _this = _super.call(this, scene.getEngine(), name) || this;
  73896. // Members
  73897. /**
  73898. * The PassPostProcess id in the pipeline that contains the original scene color
  73899. */
  73900. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73901. /**
  73902. * The SSAO PostProcess id in the pipeline
  73903. */
  73904. _this.SSAORenderEffect = "SSAORenderEffect";
  73905. /**
  73906. * The horizontal blur PostProcess id in the pipeline
  73907. */
  73908. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73909. /**
  73910. * The vertical blur PostProcess id in the pipeline
  73911. */
  73912. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73913. /**
  73914. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73915. */
  73916. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73917. /**
  73918. * The output strength of the SSAO post-process. Default value is 1.0.
  73919. */
  73920. _this.totalStrength = 1.0;
  73921. /**
  73922. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73923. */
  73924. _this.maxZ = 100.0;
  73925. /**
  73926. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73927. */
  73928. _this.minZAspect = 0.2;
  73929. /**
  73930. * Number of samples used for the SSAO calculations. Default value is 8
  73931. */
  73932. _this._samples = 8;
  73933. /**
  73934. * Are we using bilateral blur ?
  73935. */
  73936. _this._expensiveBlur = true;
  73937. /**
  73938. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73939. */
  73940. _this.radius = 2.0;
  73941. /**
  73942. * The base color of the SSAO post-process
  73943. * The final result is "base + ssao" between [0, 1]
  73944. */
  73945. _this.base = 0.1;
  73946. _this._firstUpdate = true;
  73947. _this._scene = scene;
  73948. _this._ratio = ratio;
  73949. if (!_this.isSupported) {
  73950. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73951. return _this;
  73952. }
  73953. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73954. var blurRatio = _this._ratio.blurRatio || ratio;
  73955. // Set up assets
  73956. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73957. _this._createRandomTexture();
  73958. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73959. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73960. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73961. _this._createSSAOPostProcess(1.0);
  73962. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73963. _this._createSSAOCombinePostProcess(blurRatio);
  73964. // Set up pipeline
  73965. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73966. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73967. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73968. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73969. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73970. // Finish
  73971. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73972. if (cameras)
  73973. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73974. return _this;
  73975. }
  73976. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73977. get: function () {
  73978. return this._samples;
  73979. },
  73980. set: function (n) {
  73981. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73982. this._samples = n;
  73983. this._sampleSphere = this._generateHemisphere();
  73984. this._firstUpdate = true;
  73985. },
  73986. enumerable: true,
  73987. configurable: true
  73988. });
  73989. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73990. get: function () {
  73991. return this._expensiveBlur;
  73992. },
  73993. set: function (b) {
  73994. 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"]);
  73995. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73996. this._expensiveBlur = b;
  73997. this._firstUpdate = true;
  73998. },
  73999. enumerable: true,
  74000. configurable: true
  74001. });
  74002. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74003. /**
  74004. * Support test.
  74005. */
  74006. get: function () {
  74007. var engine = BABYLON.Engine.LastCreatedEngine;
  74008. if (!engine) {
  74009. return false;
  74010. }
  74011. return engine.getCaps().drawBuffersExtension;
  74012. },
  74013. enumerable: true,
  74014. configurable: true
  74015. });
  74016. // Public Methods
  74017. /**
  74018. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74019. */
  74020. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74021. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74022. for (var i = 0; i < this._scene.cameras.length; i++) {
  74023. var camera = this._scene.cameras[i];
  74024. this._originalColorPostProcess.dispose(camera);
  74025. this._ssaoPostProcess.dispose(camera);
  74026. this._blurHPostProcess.dispose(camera);
  74027. this._blurVPostProcess.dispose(camera);
  74028. this._ssaoCombinePostProcess.dispose(camera);
  74029. }
  74030. this._randomTexture.dispose();
  74031. if (disableGeometryBufferRenderer)
  74032. this._scene.disableGeometryBufferRenderer();
  74033. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74034. _super.prototype.dispose.call(this);
  74035. };
  74036. // Private Methods
  74037. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74038. var _this = this;
  74039. this._samplerOffsets = [];
  74040. var expensive = this.expensiveBlur;
  74041. for (var i = -8; i < 8; i++) {
  74042. this._samplerOffsets.push(i * 2 + 0.5);
  74043. }
  74044. 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");
  74045. this._blurHPostProcess.onApply = function (effect) {
  74046. if (!_this._scene.activeCamera) {
  74047. return;
  74048. }
  74049. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74050. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74051. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74052. effect.setFloat("radius", _this.radius);
  74053. effect.setTexture("depthSampler", _this._depthTexture);
  74054. if (_this._firstUpdate) {
  74055. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74056. }
  74057. };
  74058. 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");
  74059. this._blurVPostProcess.onApply = function (effect) {
  74060. if (!_this._scene.activeCamera) {
  74061. return;
  74062. }
  74063. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74064. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74065. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74066. effect.setFloat("radius", _this.radius);
  74067. effect.setTexture("depthSampler", _this._depthTexture);
  74068. if (_this._firstUpdate) {
  74069. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74070. _this._firstUpdate = false;
  74071. }
  74072. };
  74073. };
  74074. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74075. this._firstUpdate = true;
  74076. _super.prototype._rebuild.call(this);
  74077. };
  74078. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74079. var numSamples = this.samples;
  74080. var result = [];
  74081. var vector, scale;
  74082. var rand = function (min, max) {
  74083. return Math.random() * (max - min) + min;
  74084. };
  74085. var i = 0;
  74086. while (i < numSamples) {
  74087. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74088. vector.normalize();
  74089. scale = i / numSamples;
  74090. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74091. vector.scaleInPlace(scale);
  74092. result.push(vector.x, vector.y, vector.z);
  74093. i++;
  74094. }
  74095. return result;
  74096. };
  74097. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74098. var _this = this;
  74099. var numSamples = this.samples;
  74100. this._sampleSphere = this._generateHemisphere();
  74101. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74102. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74103. "base", "range", "projection", "near", "far", "texelSize",
  74104. "xViewport", "yViewport", "maxZ", "minZAspect"
  74105. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74106. this._ssaoPostProcess.onApply = function (effect) {
  74107. if (_this._firstUpdate) {
  74108. effect.setArray3("sampleSphere", _this._sampleSphere);
  74109. effect.setFloat("randTextureTiles", 4.0);
  74110. }
  74111. if (!_this._scene.activeCamera) {
  74112. return;
  74113. }
  74114. effect.setFloat("samplesFactor", 1 / _this.samples);
  74115. effect.setFloat("totalStrength", _this.totalStrength);
  74116. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74117. effect.setFloat("radius", _this.radius);
  74118. effect.setFloat("maxZ", _this.maxZ);
  74119. effect.setFloat("minZAspect", _this.minZAspect);
  74120. effect.setFloat("base", _this.base);
  74121. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74122. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74123. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74124. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74125. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74126. effect.setTexture("textureSampler", _this._depthTexture);
  74127. effect.setTexture("normalSampler", _this._normalTexture);
  74128. effect.setTexture("randomSampler", _this._randomTexture);
  74129. };
  74130. };
  74131. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74132. var _this = this;
  74133. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74134. this._ssaoCombinePostProcess.onApply = function (effect) {
  74135. var viewport = _this._scene.activeCamera.viewport;
  74136. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74137. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74138. };
  74139. };
  74140. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74141. var size = 512;
  74142. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74143. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74144. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74145. var context = this._randomTexture.getContext();
  74146. var rand = function (min, max) {
  74147. return Math.random() * (max - min) + min;
  74148. };
  74149. var randVector = BABYLON.Vector3.Zero();
  74150. for (var x = 0; x < size; x++) {
  74151. for (var y = 0; y < size; y++) {
  74152. randVector.x = rand(0.0, 1.0);
  74153. randVector.y = rand(0.0, 1.0);
  74154. randVector.z = 0.0;
  74155. randVector.normalize();
  74156. randVector.scaleInPlace(255);
  74157. randVector.x = Math.floor(randVector.x);
  74158. randVector.y = Math.floor(randVector.y);
  74159. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74160. context.fillRect(x, y, 1, 1);
  74161. }
  74162. }
  74163. this._randomTexture.update(false);
  74164. };
  74165. /**
  74166. * Serialize the rendering pipeline (Used when exporting)
  74167. * @returns the serialized object
  74168. */
  74169. SSAO2RenderingPipeline.prototype.serialize = function () {
  74170. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74171. serializationObject.customType = "SSAO2RenderingPipeline";
  74172. return serializationObject;
  74173. };
  74174. /**
  74175. * Parse the serialized pipeline
  74176. * @param source Source pipeline.
  74177. * @param scene The scene to load the pipeline to.
  74178. * @param rootUrl The URL of the serialized pipeline.
  74179. * @returns An instantiated pipeline from the serialized object.
  74180. */
  74181. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74182. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74183. };
  74184. __decorate([
  74185. BABYLON.serialize()
  74186. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74187. __decorate([
  74188. BABYLON.serialize()
  74189. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74190. __decorate([
  74191. BABYLON.serialize()
  74192. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74193. __decorate([
  74194. BABYLON.serialize("samples")
  74195. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74196. __decorate([
  74197. BABYLON.serialize()
  74198. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74199. __decorate([
  74200. BABYLON.serialize("expensiveBlur")
  74201. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74202. __decorate([
  74203. BABYLON.serialize()
  74204. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74205. __decorate([
  74206. BABYLON.serialize()
  74207. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74208. return SSAO2RenderingPipeline;
  74209. }(BABYLON.PostProcessRenderPipeline));
  74210. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74211. })(BABYLON || (BABYLON = {}));
  74212. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74213. // BABYLON.JS Chromatic Aberration GLSL Shader
  74214. // Author: Olivier Guyot
  74215. // Separates very slightly R, G and B colors on the edges of the screen
  74216. // Inspired by Francois Tarlier & Martins Upitis
  74217. var BABYLON;
  74218. (function (BABYLON) {
  74219. var LensRenderingPipeline = /** @class */ (function (_super) {
  74220. __extends(LensRenderingPipeline, _super);
  74221. /**
  74222. * @constructor
  74223. *
  74224. * Effect parameters are as follow:
  74225. * {
  74226. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74227. * edge_blur: number; // from 0 to x (1 for realism)
  74228. * distortion: number; // from 0 to x (1 for realism)
  74229. * grain_amount: number; // from 0 to 1
  74230. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74231. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74232. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74233. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74234. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74235. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74236. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74237. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74238. * }
  74239. * Note: if an effect parameter is unset, effect is disabled
  74240. *
  74241. * @param {string} name - The rendering pipeline name
  74242. * @param {object} parameters - An object containing all parameters (see above)
  74243. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74244. * @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)
  74245. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74246. */
  74247. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74248. if (ratio === void 0) { ratio = 1.0; }
  74249. var _this = _super.call(this, scene.getEngine(), name) || this;
  74250. // Lens effects can be of the following:
  74251. // - chromatic aberration (slight shift of RGB colors)
  74252. // - blur on the edge of the lens
  74253. // - lens distortion
  74254. // - depth-of-field blur & highlights enhancing
  74255. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74256. // - grain effect (noise or custom texture)
  74257. // Two additional texture samplers are needed:
  74258. // - depth map (for depth-of-field)
  74259. // - grain texture
  74260. /**
  74261. * The chromatic aberration PostProcess id in the pipeline
  74262. */
  74263. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74264. /**
  74265. * The highlights enhancing PostProcess id in the pipeline
  74266. */
  74267. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74268. /**
  74269. * The depth-of-field PostProcess id in the pipeline
  74270. */
  74271. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74272. _this._scene = scene;
  74273. // Fetch texture samplers
  74274. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74275. if (parameters.grain_texture) {
  74276. _this._grainTexture = parameters.grain_texture;
  74277. }
  74278. else {
  74279. _this._createGrainTexture();
  74280. }
  74281. // save parameters
  74282. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74283. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74284. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74285. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74286. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74287. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74288. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74289. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74290. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74291. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74292. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74293. // Create effects
  74294. _this._createChromaticAberrationPostProcess(ratio);
  74295. _this._createHighlightsPostProcess(ratio);
  74296. _this._createDepthOfFieldPostProcess(ratio / 4);
  74297. // Set up pipeline
  74298. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74299. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74300. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74301. if (_this._highlightsGain === -1) {
  74302. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74303. }
  74304. // Finish
  74305. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74306. if (cameras) {
  74307. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74308. }
  74309. return _this;
  74310. }
  74311. // public methods (self explanatory)
  74312. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74313. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74314. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74315. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74316. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74317. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74318. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74319. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74320. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74321. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74322. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74323. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74324. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74325. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74326. };
  74327. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74328. this._highlightsPostProcess.updateEffect();
  74329. };
  74330. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74331. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74332. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74333. this._highlightsGain = amount;
  74334. };
  74335. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74336. if (this._highlightsGain === -1) {
  74337. this._highlightsGain = 1.0;
  74338. }
  74339. this._highlightsThreshold = amount;
  74340. };
  74341. LensRenderingPipeline.prototype.disableHighlights = function () {
  74342. this._highlightsGain = -1;
  74343. };
  74344. /**
  74345. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74346. */
  74347. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74348. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74349. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74350. this._chromaticAberrationPostProcess = null;
  74351. this._highlightsPostProcess = null;
  74352. this._depthOfFieldPostProcess = null;
  74353. this._grainTexture.dispose();
  74354. if (disableDepthRender)
  74355. this._scene.disableDepthRenderer();
  74356. };
  74357. // colors shifting and distortion
  74358. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74359. var _this = this;
  74360. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74361. [], // samplers
  74362. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74363. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74364. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74365. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74366. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74367. effect.setFloat('radialIntensity', 1);
  74368. effect.setFloat2('direction', 17, 17);
  74369. effect.setFloat2('centerPosition', 0.5, 0.5);
  74370. };
  74371. };
  74372. // highlights enhancing
  74373. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74374. var _this = this;
  74375. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74376. [], // samplers
  74377. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74378. this._highlightsPostProcess.onApply = function (effect) {
  74379. effect.setFloat('gain', _this._highlightsGain);
  74380. effect.setFloat('threshold', _this._highlightsThreshold);
  74381. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74382. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74383. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74384. };
  74385. };
  74386. // colors shifting and distortion
  74387. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74388. var _this = this;
  74389. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74390. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74391. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74392. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74393. this._depthOfFieldPostProcess.onApply = function (effect) {
  74394. effect.setTexture("depthSampler", _this._depthTexture);
  74395. effect.setTexture("grainSampler", _this._grainTexture);
  74396. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74397. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74398. effect.setFloat('grain_amount', _this._grainAmount);
  74399. effect.setBool('blur_noise', _this._blurNoise);
  74400. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74401. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74402. effect.setFloat('distortion', _this._distortion);
  74403. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74404. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74405. effect.setFloat('aperture', _this._dofAperture);
  74406. effect.setFloat('darken', _this._dofDarken);
  74407. effect.setFloat('edge_blur', _this._edgeBlur);
  74408. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74409. if (_this._scene.activeCamera) {
  74410. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74411. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74412. }
  74413. };
  74414. };
  74415. // creates a black and white random noise texture, 512x512
  74416. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74417. var size = 512;
  74418. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74419. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74420. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74421. var context = this._grainTexture.getContext();
  74422. var rand = function (min, max) {
  74423. return Math.random() * (max - min) + min;
  74424. };
  74425. var value;
  74426. for (var x = 0; x < size; x++) {
  74427. for (var y = 0; y < size; y++) {
  74428. value = Math.floor(rand(0.42, 0.58) * 255);
  74429. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74430. context.fillRect(x, y, 1, 1);
  74431. }
  74432. }
  74433. this._grainTexture.update(false);
  74434. };
  74435. return LensRenderingPipeline;
  74436. }(BABYLON.PostProcessRenderPipeline));
  74437. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74438. })(BABYLON || (BABYLON = {}));
  74439. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74440. var BABYLON;
  74441. (function (BABYLON) {
  74442. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74443. __extends(StandardRenderingPipeline, _super);
  74444. /**
  74445. * @constructor
  74446. * @param {string} name - The rendering pipeline name
  74447. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74448. * @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)
  74449. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74450. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74451. */
  74452. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74453. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74454. var _this = _super.call(this, scene.getEngine(), name) || this;
  74455. _this.downSampleX4PostProcess = null;
  74456. _this.brightPassPostProcess = null;
  74457. _this.blurHPostProcesses = [];
  74458. _this.blurVPostProcesses = [];
  74459. _this.textureAdderPostProcess = null;
  74460. _this.volumetricLightPostProcess = null;
  74461. _this.volumetricLightSmoothXPostProcess = null;
  74462. _this.volumetricLightSmoothYPostProcess = null;
  74463. _this.volumetricLightMergePostProces = null;
  74464. _this.volumetricLightFinalPostProcess = null;
  74465. _this.luminancePostProcess = null;
  74466. _this.luminanceDownSamplePostProcesses = [];
  74467. _this.hdrPostProcess = null;
  74468. _this.textureAdderFinalPostProcess = null;
  74469. _this.lensFlareFinalPostProcess = null;
  74470. _this.hdrFinalPostProcess = null;
  74471. _this.lensFlarePostProcess = null;
  74472. _this.lensFlareComposePostProcess = null;
  74473. _this.motionBlurPostProcess = null;
  74474. _this.depthOfFieldPostProcess = null;
  74475. // Values
  74476. _this.brightThreshold = 1.0;
  74477. _this.blurWidth = 512.0;
  74478. _this.horizontalBlur = false;
  74479. _this.exposure = 1.0;
  74480. _this.lensTexture = null;
  74481. _this.volumetricLightCoefficient = 0.2;
  74482. _this.volumetricLightPower = 4.0;
  74483. _this.volumetricLightBlurScale = 64.0;
  74484. _this.sourceLight = null;
  74485. _this.hdrMinimumLuminance = 1.0;
  74486. _this.hdrDecreaseRate = 0.5;
  74487. _this.hdrIncreaseRate = 0.5;
  74488. _this.lensColorTexture = null;
  74489. _this.lensFlareStrength = 20.0;
  74490. _this.lensFlareGhostDispersal = 1.4;
  74491. _this.lensFlareHaloWidth = 0.7;
  74492. _this.lensFlareDistortionStrength = 16.0;
  74493. _this.lensStarTexture = null;
  74494. _this.lensFlareDirtTexture = null;
  74495. _this.depthOfFieldDistance = 10.0;
  74496. _this.depthOfFieldBlurWidth = 64.0;
  74497. _this.motionStrength = 1.0;
  74498. // IAnimatable
  74499. _this.animations = [];
  74500. _this._currentDepthOfFieldSource = null;
  74501. _this._hdrCurrentLuminance = 1.0;
  74502. // Getters and setters
  74503. _this._bloomEnabled = true;
  74504. _this._depthOfFieldEnabled = false;
  74505. _this._vlsEnabled = false;
  74506. _this._lensFlareEnabled = false;
  74507. _this._hdrEnabled = false;
  74508. _this._motionBlurEnabled = false;
  74509. _this._motionBlurSamples = 64.0;
  74510. _this._volumetricLightStepsCount = 50.0;
  74511. _this._cameras = cameras || [];
  74512. // Initialize
  74513. _this._scene = scene;
  74514. _this._basePostProcess = originalPostProcess;
  74515. _this._ratio = ratio;
  74516. // Misc
  74517. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74518. // Finish
  74519. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74520. _this._buildPipeline();
  74521. return _this;
  74522. }
  74523. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74524. get: function () {
  74525. return this._bloomEnabled;
  74526. },
  74527. set: function (enabled) {
  74528. if (this._bloomEnabled === enabled) {
  74529. return;
  74530. }
  74531. this._bloomEnabled = enabled;
  74532. this._buildPipeline();
  74533. },
  74534. enumerable: true,
  74535. configurable: true
  74536. });
  74537. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74538. get: function () {
  74539. return this._depthOfFieldEnabled;
  74540. },
  74541. set: function (enabled) {
  74542. if (this._depthOfFieldEnabled === enabled) {
  74543. return;
  74544. }
  74545. this._depthOfFieldEnabled = enabled;
  74546. this._buildPipeline();
  74547. },
  74548. enumerable: true,
  74549. configurable: true
  74550. });
  74551. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74552. get: function () {
  74553. return this._lensFlareEnabled;
  74554. },
  74555. set: function (enabled) {
  74556. if (this._lensFlareEnabled === enabled) {
  74557. return;
  74558. }
  74559. this._lensFlareEnabled = enabled;
  74560. this._buildPipeline();
  74561. },
  74562. enumerable: true,
  74563. configurable: true
  74564. });
  74565. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74566. get: function () {
  74567. return this._hdrEnabled;
  74568. },
  74569. set: function (enabled) {
  74570. if (this._hdrEnabled === enabled) {
  74571. return;
  74572. }
  74573. this._hdrEnabled = enabled;
  74574. this._buildPipeline();
  74575. },
  74576. enumerable: true,
  74577. configurable: true
  74578. });
  74579. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74580. get: function () {
  74581. return this._vlsEnabled;
  74582. },
  74583. set: function (enabled) {
  74584. if (this._vlsEnabled === enabled) {
  74585. return;
  74586. }
  74587. if (enabled) {
  74588. var geometry = this._scene.enableGeometryBufferRenderer();
  74589. if (!geometry) {
  74590. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74591. return;
  74592. }
  74593. }
  74594. this._vlsEnabled = enabled;
  74595. this._buildPipeline();
  74596. },
  74597. enumerable: true,
  74598. configurable: true
  74599. });
  74600. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74601. get: function () {
  74602. return this._motionBlurEnabled;
  74603. },
  74604. set: function (enabled) {
  74605. if (this._motionBlurEnabled === enabled) {
  74606. return;
  74607. }
  74608. this._motionBlurEnabled = enabled;
  74609. this._buildPipeline();
  74610. },
  74611. enumerable: true,
  74612. configurable: true
  74613. });
  74614. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74615. get: function () {
  74616. return this._volumetricLightStepsCount;
  74617. },
  74618. set: function (count) {
  74619. if (this.volumetricLightPostProcess) {
  74620. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74621. }
  74622. this._volumetricLightStepsCount = count;
  74623. },
  74624. enumerable: true,
  74625. configurable: true
  74626. });
  74627. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74628. get: function () {
  74629. return this._motionBlurSamples;
  74630. },
  74631. set: function (samples) {
  74632. if (this.motionBlurPostProcess) {
  74633. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74634. }
  74635. this._motionBlurSamples = samples;
  74636. },
  74637. enumerable: true,
  74638. configurable: true
  74639. });
  74640. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74641. var _this = this;
  74642. var ratio = this._ratio;
  74643. var scene = this._scene;
  74644. this._disposePostProcesses();
  74645. this._reset();
  74646. // Create pass post-process
  74647. if (!this._basePostProcess) {
  74648. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74649. this.originalPostProcess.onApply = function (effect) {
  74650. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74651. };
  74652. }
  74653. else {
  74654. this.originalPostProcess = this._basePostProcess;
  74655. }
  74656. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74657. this._currentDepthOfFieldSource = this.originalPostProcess;
  74658. if (this._bloomEnabled) {
  74659. // Create down sample X4 post-process
  74660. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74661. // Create bright pass post-process
  74662. this._createBrightPassPostProcess(scene, ratio / 2);
  74663. // Create gaussian blur post-processes (down sampling blurs)
  74664. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74665. // Create texture adder post-process
  74666. this._createTextureAdderPostProcess(scene, ratio);
  74667. // Create depth-of-field source post-process
  74668. 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);
  74669. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74670. }
  74671. if (this._vlsEnabled) {
  74672. // Create volumetric light
  74673. this._createVolumetricLightPostProcess(scene, ratio);
  74674. // Create volumetric light final post-process
  74675. 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);
  74676. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74677. }
  74678. if (this._lensFlareEnabled) {
  74679. // Create lens flare post-process
  74680. this._createLensFlarePostProcess(scene, ratio);
  74681. // Create depth-of-field source post-process post lens-flare and disable it now
  74682. 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);
  74683. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74684. }
  74685. if (this._hdrEnabled) {
  74686. // Create luminance
  74687. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74688. // Create HDR
  74689. this._createHdrPostProcess(scene, ratio);
  74690. // Create depth-of-field source post-process post hdr and disable it now
  74691. 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);
  74692. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74693. }
  74694. if (this._depthOfFieldEnabled) {
  74695. // Create gaussian blur used by depth-of-field
  74696. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74697. // Create depth-of-field post-process
  74698. this._createDepthOfFieldPostProcess(scene, ratio);
  74699. }
  74700. if (this._motionBlurEnabled) {
  74701. // Create motion blur post-process
  74702. this._createMotionBlurPostProcess(scene, ratio);
  74703. }
  74704. if (this._cameras !== null) {
  74705. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74706. }
  74707. };
  74708. // Down Sample X4 Post-Processs
  74709. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74710. var _this = this;
  74711. var downSampleX4Offsets = new Array(32);
  74712. 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);
  74713. this.downSampleX4PostProcess.onApply = function (effect) {
  74714. var id = 0;
  74715. var width = _this.downSampleX4PostProcess.width;
  74716. var height = _this.downSampleX4PostProcess.height;
  74717. for (var i = -2; i < 2; i++) {
  74718. for (var j = -2; j < 2; j++) {
  74719. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74720. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74721. id += 2;
  74722. }
  74723. }
  74724. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74725. };
  74726. // Add to pipeline
  74727. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74728. };
  74729. // Brightpass Post-Process
  74730. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74731. var _this = this;
  74732. var brightOffsets = new Array(8);
  74733. 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);
  74734. this.brightPassPostProcess.onApply = function (effect) {
  74735. var sU = (1.0 / _this.brightPassPostProcess.width);
  74736. var sV = (1.0 / _this.brightPassPostProcess.height);
  74737. brightOffsets[0] = -0.5 * sU;
  74738. brightOffsets[1] = 0.5 * sV;
  74739. brightOffsets[2] = 0.5 * sU;
  74740. brightOffsets[3] = 0.5 * sV;
  74741. brightOffsets[4] = -0.5 * sU;
  74742. brightOffsets[5] = -0.5 * sV;
  74743. brightOffsets[6] = 0.5 * sU;
  74744. brightOffsets[7] = -0.5 * sV;
  74745. effect.setArray2("dsOffsets", brightOffsets);
  74746. effect.setFloat("brightThreshold", _this.brightThreshold);
  74747. };
  74748. // Add to pipeline
  74749. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74750. };
  74751. // Create blur H&V post-processes
  74752. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74753. var _this = this;
  74754. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74755. var engine = scene.getEngine();
  74756. 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);
  74757. 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);
  74758. blurX.onActivateObservable.add(function () {
  74759. var dw = blurX.width / engine.getRenderWidth();
  74760. blurX.kernel = _this[blurWidthKey] * dw;
  74761. });
  74762. blurY.onActivateObservable.add(function () {
  74763. var dw = blurY.height / engine.getRenderHeight();
  74764. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74765. });
  74766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74767. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74768. this.blurHPostProcesses.push(blurX);
  74769. this.blurVPostProcesses.push(blurY);
  74770. };
  74771. // Create texture adder post-process
  74772. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74773. var _this = this;
  74774. 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);
  74775. this.textureAdderPostProcess.onApply = function (effect) {
  74776. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74777. effect.setTexture("lensSampler", _this.lensTexture);
  74778. effect.setFloat("exposure", _this.exposure);
  74779. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74780. };
  74781. // Add to pipeline
  74782. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74783. };
  74784. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74785. var _this = this;
  74786. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74787. geometryRenderer.enablePosition = true;
  74788. var geometry = geometryRenderer.getGBuffer();
  74789. // Base post-process
  74790. 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));
  74791. var depthValues = BABYLON.Vector2.Zero();
  74792. this.volumetricLightPostProcess.onApply = function (effect) {
  74793. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74794. var generator = _this.sourceLight.getShadowGenerator();
  74795. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74796. effect.setTexture("positionSampler", geometry.textures[2]);
  74797. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74798. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74799. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74800. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74801. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74802. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74803. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74804. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74805. effect.setVector2("depthValues", depthValues);
  74806. }
  74807. };
  74808. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74809. // Smooth
  74810. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74811. // Merge
  74812. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74813. this.volumetricLightMergePostProces.onApply = function (effect) {
  74814. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74815. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74816. };
  74817. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74818. };
  74819. // Create luminance
  74820. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74821. var _this = this;
  74822. // Create luminance
  74823. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74824. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74825. var offsets = [];
  74826. this.luminancePostProcess.onApply = function (effect) {
  74827. var sU = (1.0 / _this.luminancePostProcess.width);
  74828. var sV = (1.0 / _this.luminancePostProcess.height);
  74829. offsets[0] = -0.5 * sU;
  74830. offsets[1] = 0.5 * sV;
  74831. offsets[2] = 0.5 * sU;
  74832. offsets[3] = 0.5 * sV;
  74833. offsets[4] = -0.5 * sU;
  74834. offsets[5] = -0.5 * sV;
  74835. offsets[6] = 0.5 * sU;
  74836. offsets[7] = -0.5 * sV;
  74837. effect.setArray2("lumOffsets", offsets);
  74838. };
  74839. // Add to pipeline
  74840. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74841. // Create down sample luminance
  74842. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74843. var size = Math.pow(3, i);
  74844. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74845. if (i === 0) {
  74846. defines += "#define FINAL_DOWN_SAMPLER";
  74847. }
  74848. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74849. this.luminanceDownSamplePostProcesses.push(postProcess);
  74850. }
  74851. // Create callbacks and add effects
  74852. var lastLuminance = this.luminancePostProcess;
  74853. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74854. var downSampleOffsets = new Array(18);
  74855. pp.onApply = function (effect) {
  74856. if (!lastLuminance) {
  74857. return;
  74858. }
  74859. var id = 0;
  74860. for (var x = -1; x < 2; x++) {
  74861. for (var y = -1; y < 2; y++) {
  74862. downSampleOffsets[id] = x / lastLuminance.width;
  74863. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74864. id += 2;
  74865. }
  74866. }
  74867. effect.setArray2("dsOffsets", downSampleOffsets);
  74868. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74869. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74870. lastLuminance = _this.luminancePostProcess;
  74871. }
  74872. else {
  74873. lastLuminance = pp;
  74874. }
  74875. };
  74876. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74877. pp.onAfterRender = function (effect) {
  74878. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74879. 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);
  74880. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74881. };
  74882. }
  74883. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74884. });
  74885. };
  74886. // Create HDR post-process
  74887. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74888. var _this = this;
  74889. 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);
  74890. var outputLiminance = 1;
  74891. var time = 0;
  74892. var lastTime = 0;
  74893. this.hdrPostProcess.onApply = function (effect) {
  74894. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74895. time += scene.getEngine().getDeltaTime();
  74896. if (outputLiminance < 0) {
  74897. outputLiminance = _this._hdrCurrentLuminance;
  74898. }
  74899. else {
  74900. var dt = (lastTime - time) / 1000.0;
  74901. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74902. outputLiminance += _this.hdrDecreaseRate * dt;
  74903. }
  74904. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74905. outputLiminance -= _this.hdrIncreaseRate * dt;
  74906. }
  74907. else {
  74908. outputLiminance = _this._hdrCurrentLuminance;
  74909. }
  74910. }
  74911. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74912. effect.setFloat("averageLuminance", outputLiminance);
  74913. lastTime = time;
  74914. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74915. };
  74916. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74917. };
  74918. // Create lens flare post-process
  74919. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74920. var _this = this;
  74921. 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);
  74922. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74923. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74924. 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);
  74925. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74926. var resolution = new BABYLON.Vector2(0, 0);
  74927. // Lens flare
  74928. this.lensFlarePostProcess.onApply = function (effect) {
  74929. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74930. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74931. effect.setFloat("strength", _this.lensFlareStrength);
  74932. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74933. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74934. // Shift
  74935. resolution.x = _this.lensFlarePostProcess.width;
  74936. resolution.y = _this.lensFlarePostProcess.height;
  74937. effect.setVector2("resolution", resolution);
  74938. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74939. };
  74940. // Compose
  74941. 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);
  74942. 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);
  74943. this.lensFlareComposePostProcess.onApply = function (effect) {
  74944. if (!_this._scene.activeCamera) {
  74945. return;
  74946. }
  74947. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74948. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74949. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74950. // Lens start rotation matrix
  74951. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74952. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74953. 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));
  74954. camRot *= 4.0;
  74955. 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);
  74956. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74957. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74958. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74959. };
  74960. };
  74961. // Create depth-of-field post-process
  74962. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74963. var _this = this;
  74964. 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);
  74965. this.depthOfFieldPostProcess.onApply = function (effect) {
  74966. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74967. effect.setTexture("depthSampler", _this._getDepthTexture());
  74968. effect.setFloat("distance", _this.depthOfFieldDistance);
  74969. };
  74970. // Add to pipeline
  74971. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74972. };
  74973. // Create motion blur post-process
  74974. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74975. var _this = this;
  74976. 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);
  74977. var motionScale = 0;
  74978. var prevViewProjection = BABYLON.Matrix.Identity();
  74979. var invViewProjection = BABYLON.Matrix.Identity();
  74980. var viewProjection = BABYLON.Matrix.Identity();
  74981. var screenSize = BABYLON.Vector2.Zero();
  74982. this.motionBlurPostProcess.onApply = function (effect) {
  74983. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74984. viewProjection.invertToRef(invViewProjection);
  74985. effect.setMatrix("inverseViewProjection", invViewProjection);
  74986. effect.setMatrix("prevViewProjection", prevViewProjection);
  74987. prevViewProjection = viewProjection;
  74988. screenSize.x = _this.motionBlurPostProcess.width;
  74989. screenSize.y = _this.motionBlurPostProcess.height;
  74990. effect.setVector2("screenSize", screenSize);
  74991. motionScale = scene.getEngine().getFps() / 60.0;
  74992. effect.setFloat("motionScale", motionScale);
  74993. effect.setFloat("motionStrength", _this.motionStrength);
  74994. effect.setTexture("depthSampler", _this._getDepthTexture());
  74995. };
  74996. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74997. };
  74998. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74999. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75000. var renderer = this._scene.enableGeometryBufferRenderer();
  75001. return renderer.getGBuffer().textures[0];
  75002. }
  75003. return this._scene.enableDepthRenderer().getDepthMap();
  75004. };
  75005. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75006. for (var i = 0; i < this._cameras.length; i++) {
  75007. var camera = this._cameras[i];
  75008. if (this.originalPostProcess) {
  75009. this.originalPostProcess.dispose(camera);
  75010. }
  75011. if (this.downSampleX4PostProcess) {
  75012. this.downSampleX4PostProcess.dispose(camera);
  75013. }
  75014. if (this.brightPassPostProcess) {
  75015. this.brightPassPostProcess.dispose(camera);
  75016. }
  75017. if (this.textureAdderPostProcess) {
  75018. this.textureAdderPostProcess.dispose(camera);
  75019. }
  75020. if (this.textureAdderFinalPostProcess) {
  75021. this.textureAdderFinalPostProcess.dispose(camera);
  75022. }
  75023. if (this.volumetricLightPostProcess) {
  75024. this.volumetricLightPostProcess.dispose(camera);
  75025. }
  75026. if (this.volumetricLightSmoothXPostProcess) {
  75027. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75028. }
  75029. if (this.volumetricLightSmoothYPostProcess) {
  75030. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75031. }
  75032. if (this.volumetricLightMergePostProces) {
  75033. this.volumetricLightMergePostProces.dispose(camera);
  75034. }
  75035. if (this.volumetricLightFinalPostProcess) {
  75036. this.volumetricLightFinalPostProcess.dispose(camera);
  75037. }
  75038. if (this.lensFlarePostProcess) {
  75039. this.lensFlarePostProcess.dispose(camera);
  75040. }
  75041. if (this.lensFlareComposePostProcess) {
  75042. this.lensFlareComposePostProcess.dispose(camera);
  75043. }
  75044. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75045. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75046. }
  75047. if (this.luminancePostProcess) {
  75048. this.luminancePostProcess.dispose(camera);
  75049. }
  75050. if (this.hdrPostProcess) {
  75051. this.hdrPostProcess.dispose(camera);
  75052. }
  75053. if (this.hdrFinalPostProcess) {
  75054. this.hdrFinalPostProcess.dispose(camera);
  75055. }
  75056. if (this.depthOfFieldPostProcess) {
  75057. this.depthOfFieldPostProcess.dispose(camera);
  75058. }
  75059. if (this.motionBlurPostProcess) {
  75060. this.motionBlurPostProcess.dispose(camera);
  75061. }
  75062. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75063. this.blurHPostProcesses[j].dispose(camera);
  75064. }
  75065. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75066. this.blurVPostProcesses[j].dispose(camera);
  75067. }
  75068. }
  75069. this.originalPostProcess = null;
  75070. this.downSampleX4PostProcess = null;
  75071. this.brightPassPostProcess = null;
  75072. this.textureAdderPostProcess = null;
  75073. this.textureAdderFinalPostProcess = null;
  75074. this.volumetricLightPostProcess = null;
  75075. this.volumetricLightSmoothXPostProcess = null;
  75076. this.volumetricLightSmoothYPostProcess = null;
  75077. this.volumetricLightMergePostProces = null;
  75078. this.volumetricLightFinalPostProcess = null;
  75079. this.lensFlarePostProcess = null;
  75080. this.lensFlareComposePostProcess = null;
  75081. this.luminancePostProcess = null;
  75082. this.hdrPostProcess = null;
  75083. this.hdrFinalPostProcess = null;
  75084. this.depthOfFieldPostProcess = null;
  75085. this.motionBlurPostProcess = null;
  75086. this.luminanceDownSamplePostProcesses = [];
  75087. this.blurHPostProcesses = [];
  75088. this.blurVPostProcesses = [];
  75089. };
  75090. /**
  75091. * Dispose of the pipeline and stop all post processes
  75092. */
  75093. StandardRenderingPipeline.prototype.dispose = function () {
  75094. this._disposePostProcesses();
  75095. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75096. _super.prototype.dispose.call(this);
  75097. };
  75098. /**
  75099. * Serialize the rendering pipeline (Used when exporting)
  75100. * @returns the serialized object
  75101. */
  75102. StandardRenderingPipeline.prototype.serialize = function () {
  75103. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75104. if (this.sourceLight) {
  75105. serializationObject.sourceLightId = this.sourceLight.id;
  75106. }
  75107. serializationObject.customType = "StandardRenderingPipeline";
  75108. return serializationObject;
  75109. };
  75110. /**
  75111. * Parse the serialized pipeline
  75112. * @param source Source pipeline.
  75113. * @param scene The scene to load the pipeline to.
  75114. * @param rootUrl The URL of the serialized pipeline.
  75115. * @returns An instantiated pipeline from the serialized object.
  75116. */
  75117. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75118. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75119. if (source.sourceLightId) {
  75120. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75121. }
  75122. return p;
  75123. };
  75124. // Luminance steps
  75125. StandardRenderingPipeline.LuminanceSteps = 6;
  75126. __decorate([
  75127. BABYLON.serialize()
  75128. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75129. __decorate([
  75130. BABYLON.serialize()
  75131. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75132. __decorate([
  75133. BABYLON.serialize()
  75134. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75135. __decorate([
  75136. BABYLON.serialize()
  75137. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75138. __decorate([
  75139. BABYLON.serializeAsTexture("lensTexture")
  75140. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75141. __decorate([
  75142. BABYLON.serialize()
  75143. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75144. __decorate([
  75145. BABYLON.serialize()
  75146. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75147. __decorate([
  75148. BABYLON.serialize()
  75149. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75150. __decorate([
  75151. BABYLON.serialize()
  75152. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75153. __decorate([
  75154. BABYLON.serialize()
  75155. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75156. __decorate([
  75157. BABYLON.serialize()
  75158. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75159. __decorate([
  75160. BABYLON.serializeAsTexture("lensColorTexture")
  75161. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75162. __decorate([
  75163. BABYLON.serialize()
  75164. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75165. __decorate([
  75166. BABYLON.serialize()
  75167. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75168. __decorate([
  75169. BABYLON.serialize()
  75170. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75171. __decorate([
  75172. BABYLON.serialize()
  75173. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75174. __decorate([
  75175. BABYLON.serializeAsTexture("lensStarTexture")
  75176. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75177. __decorate([
  75178. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75179. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75180. __decorate([
  75181. BABYLON.serialize()
  75182. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75183. __decorate([
  75184. BABYLON.serialize()
  75185. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75186. __decorate([
  75187. BABYLON.serialize()
  75188. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75189. __decorate([
  75190. BABYLON.serialize()
  75191. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75192. __decorate([
  75193. BABYLON.serialize()
  75194. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75195. __decorate([
  75196. BABYLON.serialize()
  75197. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75198. __decorate([
  75199. BABYLON.serialize()
  75200. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75201. __decorate([
  75202. BABYLON.serialize()
  75203. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75204. __decorate([
  75205. BABYLON.serialize()
  75206. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75207. __decorate([
  75208. BABYLON.serialize()
  75209. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75210. __decorate([
  75211. BABYLON.serialize()
  75212. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75213. __decorate([
  75214. BABYLON.serialize()
  75215. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75216. return StandardRenderingPipeline;
  75217. }(BABYLON.PostProcessRenderPipeline));
  75218. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75219. })(BABYLON || (BABYLON = {}));
  75220. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75221. var BABYLON;
  75222. (function (BABYLON) {
  75223. var FxaaPostProcess = /** @class */ (function (_super) {
  75224. __extends(FxaaPostProcess, _super);
  75225. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75226. if (camera === void 0) { camera = null; }
  75227. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75228. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75229. var defines = _this._getDefines();
  75230. _this.updateEffect(defines);
  75231. _this.onApplyObservable.add(function (effect) {
  75232. var texelSize = _this.texelSize;
  75233. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75234. });
  75235. return _this;
  75236. }
  75237. FxaaPostProcess.prototype._getDefines = function () {
  75238. var engine = this.getEngine();
  75239. if (!engine) {
  75240. return null;
  75241. }
  75242. var glInfo = engine.getGlInfo();
  75243. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75244. return "#define MALI 1\n";
  75245. }
  75246. return null;
  75247. };
  75248. return FxaaPostProcess;
  75249. }(BABYLON.PostProcess));
  75250. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75251. })(BABYLON || (BABYLON = {}));
  75252. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75253. var BABYLON;
  75254. (function (BABYLON) {
  75255. /**
  75256. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75257. */
  75258. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75259. __extends(ChromaticAberrationPostProcess, _super);
  75260. /**
  75261. * Creates a new instance ChromaticAberrationPostProcess
  75262. * @param name The name of the effect.
  75263. * @param screenWidth The width of the screen to apply the effect on.
  75264. * @param screenHeight The height of the screen to apply the effect on.
  75265. * @param options The required width/height ratio to downsize to before computing the render pass.
  75266. * @param camera The camera to apply the render pass to.
  75267. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75268. * @param engine The engine which the post process will be applied. (default: current engine)
  75269. * @param reusable If the post process can be reused on the same frame. (default: false)
  75270. * @param textureType Type of textures used when performing the post process. (default: 0)
  75271. * @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)
  75272. */
  75273. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75274. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75275. if (blockCompilation === void 0) { blockCompilation = false; }
  75276. 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;
  75277. /**
  75278. * The amount of seperation of rgb channels (default: 30)
  75279. */
  75280. _this.aberrationAmount = 30;
  75281. /**
  75282. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75283. */
  75284. _this.radialIntensity = 0;
  75285. /**
  75286. * 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))
  75287. */
  75288. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75289. /**
  75290. * 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))
  75291. */
  75292. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75293. _this.onApplyObservable.add(function (effect) {
  75294. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75295. effect.setFloat('screen_width', screenWidth);
  75296. effect.setFloat('screen_height', screenHeight);
  75297. effect.setFloat('radialIntensity', _this.radialIntensity);
  75298. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75299. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75300. });
  75301. return _this;
  75302. }
  75303. return ChromaticAberrationPostProcess;
  75304. }(BABYLON.PostProcess));
  75305. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75306. })(BABYLON || (BABYLON = {}));
  75307. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75308. var BABYLON;
  75309. (function (BABYLON) {
  75310. /**
  75311. * The GrainPostProcess adds noise to the image at mid luminance levels
  75312. */
  75313. var GrainPostProcess = /** @class */ (function (_super) {
  75314. __extends(GrainPostProcess, _super);
  75315. /**
  75316. * Creates a new instance of @see GrainPostProcess
  75317. * @param name The name of the effect.
  75318. * @param options The required width/height ratio to downsize to before computing the render pass.
  75319. * @param camera The camera to apply the render pass to.
  75320. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75321. * @param engine The engine which the post process will be applied. (default: current engine)
  75322. * @param reusable If the post process can be reused on the same frame. (default: false)
  75323. * @param textureType Type of textures used when performing the post process. (default: 0)
  75324. * @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)
  75325. */
  75326. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75327. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75328. if (blockCompilation === void 0) { blockCompilation = false; }
  75329. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75330. /**
  75331. * The intensity of the grain added (default: 30)
  75332. */
  75333. _this.intensity = 30;
  75334. /**
  75335. * If the grain should be randomized on every frame
  75336. */
  75337. _this.animated = false;
  75338. _this.onApplyObservable.add(function (effect) {
  75339. effect.setFloat('intensity', _this.intensity);
  75340. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75341. });
  75342. return _this;
  75343. }
  75344. return GrainPostProcess;
  75345. }(BABYLON.PostProcess));
  75346. BABYLON.GrainPostProcess = GrainPostProcess;
  75347. })(BABYLON || (BABYLON = {}));
  75348. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75349. var BABYLON;
  75350. (function (BABYLON) {
  75351. /**
  75352. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75353. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75354. */
  75355. var SharpenPostProcess = /** @class */ (function (_super) {
  75356. __extends(SharpenPostProcess, _super);
  75357. /**
  75358. * Creates a new instance ConvolutionPostProcess
  75359. * @param name The name of the effect.
  75360. * @param options The required width/height ratio to downsize to before computing the render pass.
  75361. * @param camera The camera to apply the render pass to.
  75362. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75363. * @param engine The engine which the post process will be applied. (default: current engine)
  75364. * @param reusable If the post process can be reused on the same frame. (default: false)
  75365. * @param textureType Type of textures used when performing the post process. (default: 0)
  75366. * @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)
  75367. */
  75368. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75369. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75370. if (blockCompilation === void 0) { blockCompilation = false; }
  75371. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75372. /**
  75373. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75374. */
  75375. _this.colorAmount = 1.0;
  75376. /**
  75377. * How much sharpness should be applied (default: 0.3)
  75378. */
  75379. _this.edgeAmount = 0.3;
  75380. _this.onApply = function (effect) {
  75381. effect.setFloat2("screenSize", _this.width, _this.height);
  75382. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75383. };
  75384. return _this;
  75385. }
  75386. return SharpenPostProcess;
  75387. }(BABYLON.PostProcess));
  75388. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75389. })(BABYLON || (BABYLON = {}));
  75390. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75391. var BABYLON;
  75392. (function (BABYLON) {
  75393. /**
  75394. * The Blur Post Process which blurs an image based on a kernel and direction.
  75395. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75396. */
  75397. var BlurPostProcess = /** @class */ (function (_super) {
  75398. __extends(BlurPostProcess, _super);
  75399. /**
  75400. * Creates a new instance BlurPostProcess
  75401. * @param name The name of the effect.
  75402. * @param direction The direction in which to blur the image.
  75403. * @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.
  75404. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75405. * @param camera The camera to apply the render pass to.
  75406. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75407. * @param engine The engine which the post process will be applied. (default: current engine)
  75408. * @param reusable If the post process can be reused on the same frame. (default: false)
  75409. * @param textureType Type of textures used when performing the post process. (default: 0)
  75410. * @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)
  75411. */
  75412. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75413. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75414. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75415. if (defines === void 0) { defines = ""; }
  75416. if (blockCompilation === void 0) { blockCompilation = false; }
  75417. 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;
  75418. _this.direction = direction;
  75419. _this.blockCompilation = blockCompilation;
  75420. _this._packedFloat = false;
  75421. _this._staticDefines = "";
  75422. _this._staticDefines = defines;
  75423. _this.onApplyObservable.add(function (effect) {
  75424. if (_this._outputTexture) {
  75425. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75426. }
  75427. else {
  75428. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75429. }
  75430. });
  75431. _this.kernel = kernel;
  75432. return _this;
  75433. }
  75434. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75435. /**
  75436. * Gets the length in pixels of the blur sample region
  75437. */
  75438. get: function () {
  75439. return this._idealKernel;
  75440. },
  75441. /**
  75442. * Sets the length in pixels of the blur sample region
  75443. */
  75444. set: function (v) {
  75445. if (this._idealKernel === v) {
  75446. return;
  75447. }
  75448. v = Math.max(v, 1);
  75449. this._idealKernel = v;
  75450. this._kernel = this._nearestBestKernel(v);
  75451. if (!this.blockCompilation) {
  75452. this._updateParameters();
  75453. }
  75454. },
  75455. enumerable: true,
  75456. configurable: true
  75457. });
  75458. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75459. /**
  75460. * Gets wether or not the blur is unpacking/repacking floats
  75461. */
  75462. get: function () {
  75463. return this._packedFloat;
  75464. },
  75465. /**
  75466. * Sets wether or not the blur needs to unpack/repack floats
  75467. */
  75468. set: function (v) {
  75469. if (this._packedFloat === v) {
  75470. return;
  75471. }
  75472. this._packedFloat = v;
  75473. if (!this.blockCompilation) {
  75474. this._updateParameters();
  75475. }
  75476. },
  75477. enumerable: true,
  75478. configurable: true
  75479. });
  75480. /**
  75481. * Updates the effect with the current post process compile time values and recompiles the shader.
  75482. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75483. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75484. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75485. * @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
  75486. * @param onCompiled Called when the shader has been compiled.
  75487. * @param onError Called if there is an error when compiling a shader.
  75488. */
  75489. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75490. if (defines === void 0) { defines = null; }
  75491. if (uniforms === void 0) { uniforms = null; }
  75492. if (samplers === void 0) { samplers = null; }
  75493. this._updateParameters(onCompiled, onError);
  75494. };
  75495. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75496. // Generate sampling offsets and weights
  75497. var N = this._kernel;
  75498. var centerIndex = (N - 1) / 2;
  75499. // Generate Gaussian sampling weights over kernel
  75500. var offsets = [];
  75501. var weights = [];
  75502. var totalWeight = 0;
  75503. for (var i = 0; i < N; i++) {
  75504. var u = i / (N - 1);
  75505. var w = this._gaussianWeight(u * 2.0 - 1);
  75506. offsets[i] = (i - centerIndex);
  75507. weights[i] = w;
  75508. totalWeight += w;
  75509. }
  75510. // Normalize weights
  75511. for (var i = 0; i < weights.length; i++) {
  75512. weights[i] /= totalWeight;
  75513. }
  75514. // Optimize: combine samples to take advantage of hardware linear sampling
  75515. // Walk from left to center, combining pairs (symmetrically)
  75516. var linearSamplingWeights = [];
  75517. var linearSamplingOffsets = [];
  75518. var linearSamplingMap = [];
  75519. for (var i = 0; i <= centerIndex; i += 2) {
  75520. var j = Math.min(i + 1, Math.floor(centerIndex));
  75521. var singleCenterSample = i === j;
  75522. if (singleCenterSample) {
  75523. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75524. }
  75525. else {
  75526. var sharedCell = j === centerIndex;
  75527. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75528. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75529. if (offsetLinear === 0) {
  75530. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75531. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75532. }
  75533. else {
  75534. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75535. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75536. }
  75537. }
  75538. }
  75539. for (var i = 0; i < linearSamplingMap.length; i++) {
  75540. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75541. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75542. }
  75543. // Replace with optimized
  75544. offsets = linearSamplingOffsets;
  75545. weights = linearSamplingWeights;
  75546. // Generate shaders
  75547. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75548. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75549. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75550. var defines = "";
  75551. defines += this._staticDefines;
  75552. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75553. if (this._staticDefines.indexOf("DOF") != -1) {
  75554. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75555. varyingCount--;
  75556. }
  75557. for (var i = 0; i < varyingCount; i++) {
  75558. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75559. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75560. }
  75561. var depCount = 0;
  75562. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75563. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75564. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75565. depCount++;
  75566. }
  75567. if (this.packedFloat) {
  75568. defines += "#define PACKEDFLOAT 1";
  75569. }
  75570. this.blockCompilation = false;
  75571. _super.prototype.updateEffect.call(this, defines, null, null, {
  75572. varyingCount: varyingCount,
  75573. depCount: depCount
  75574. }, onCompiled, onError);
  75575. };
  75576. /**
  75577. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75578. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75579. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75580. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75581. * The gaps between physical kernels are compensated for in the weighting of the samples
  75582. * @param idealKernel Ideal blur kernel.
  75583. * @return Nearest best kernel.
  75584. */
  75585. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75586. var v = Math.round(idealKernel);
  75587. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75588. var k = _a[_i];
  75589. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75590. return Math.max(k, 3);
  75591. }
  75592. }
  75593. return Math.max(v, 3);
  75594. };
  75595. /**
  75596. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75597. * @param x The point on the Gaussian distribution to sample.
  75598. * @return the value of the Gaussian function at x.
  75599. */
  75600. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75601. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75602. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75603. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75604. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75605. // truncated at around 1.3% of peak strength.
  75606. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75607. var sigma = (1 / 3);
  75608. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75609. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75610. var weight = (1.0 / denominator) * Math.exp(exponent);
  75611. return weight;
  75612. };
  75613. /**
  75614. * Generates a string that can be used as a floating point number in GLSL.
  75615. * @param x Value to print.
  75616. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75617. * @return GLSL float string.
  75618. */
  75619. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75620. if (decimalFigures === void 0) { decimalFigures = 8; }
  75621. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75622. };
  75623. return BlurPostProcess;
  75624. }(BABYLON.PostProcess));
  75625. BABYLON.BlurPostProcess = BlurPostProcess;
  75626. })(BABYLON || (BABYLON = {}));
  75627. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75628. var BABYLON;
  75629. (function (BABYLON) {
  75630. /**
  75631. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75632. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75633. * based on samples that have a large difference in distance than the center pixel.
  75634. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75635. */
  75636. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75637. __extends(DepthOfFieldBlurPostProcess, _super);
  75638. /**
  75639. * Creates a new instance CircleOfConfusionPostProcess
  75640. * @param name The name of the effect.
  75641. * @param scene The scene the effect belongs to.
  75642. * @param direction The direction the blur should be applied.
  75643. * @param kernel The size of the kernel used to blur.
  75644. * @param options The required width/height ratio to downsize to before computing the render pass.
  75645. * @param camera The camera to apply the render pass to.
  75646. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75647. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75648. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75649. * @param engine The engine which the post process will be applied. (default: current engine)
  75650. * @param reusable If the post process can be reused on the same frame. (default: false)
  75651. * @param textureType Type of textures used when performing the post process. (default: 0)
  75652. * @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)
  75653. */
  75654. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75655. if (imageToBlur === void 0) { imageToBlur = null; }
  75656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75657. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75658. if (blockCompilation === void 0) { blockCompilation = false; }
  75659. 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;
  75660. _this.direction = direction;
  75661. _this.onApplyObservable.add(function (effect) {
  75662. if (imageToBlur != null) {
  75663. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75664. }
  75665. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75666. if (scene.activeCamera) {
  75667. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75668. }
  75669. });
  75670. return _this;
  75671. }
  75672. return DepthOfFieldBlurPostProcess;
  75673. }(BABYLON.BlurPostProcess));
  75674. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75675. })(BABYLON || (BABYLON = {}));
  75676. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75677. var BABYLON;
  75678. (function (BABYLON) {
  75679. /**
  75680. * Options to be set when merging outputs from the default pipeline.
  75681. */
  75682. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75683. function DepthOfFieldMergePostProcessOptions() {
  75684. }
  75685. return DepthOfFieldMergePostProcessOptions;
  75686. }());
  75687. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75688. /**
  75689. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75690. */
  75691. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75692. __extends(DepthOfFieldMergePostProcess, _super);
  75693. /**
  75694. * Creates a new instance of DepthOfFieldMergePostProcess
  75695. * @param name The name of the effect.
  75696. * @param originalFromInput Post process which's input will be used for the merge.
  75697. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75698. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75699. * @param options The required width/height ratio to downsize to before computing the render pass.
  75700. * @param camera The camera to apply the render pass to.
  75701. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75702. * @param engine The engine which the post process will be applied. (default: current engine)
  75703. * @param reusable If the post process can be reused on the same frame. (default: false)
  75704. * @param textureType Type of textures used when performing the post process. (default: 0)
  75705. * @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)
  75706. */
  75707. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75708. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75709. if (blockCompilation === void 0) { blockCompilation = false; }
  75710. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75711. _this.blurSteps = blurSteps;
  75712. _this.onApplyObservable.add(function (effect) {
  75713. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75714. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75715. blurSteps.forEach(function (step, index) {
  75716. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75717. });
  75718. });
  75719. if (!blockCompilation) {
  75720. _this.updateEffect();
  75721. }
  75722. return _this;
  75723. }
  75724. /**
  75725. * Updates the effect with the current post process compile time values and recompiles the shader.
  75726. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75727. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75728. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75729. * @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
  75730. * @param onCompiled Called when the shader has been compiled.
  75731. * @param onError Called if there is an error when compiling a shader.
  75732. */
  75733. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75734. if (defines === void 0) { defines = null; }
  75735. if (uniforms === void 0) { uniforms = null; }
  75736. if (samplers === void 0) { samplers = null; }
  75737. if (!defines) {
  75738. defines = "";
  75739. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75740. }
  75741. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75742. };
  75743. return DepthOfFieldMergePostProcess;
  75744. }(BABYLON.PostProcess));
  75745. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75746. })(BABYLON || (BABYLON = {}));
  75747. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75748. var BABYLON;
  75749. (function (BABYLON) {
  75750. /**
  75751. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75752. */
  75753. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75754. __extends(CircleOfConfusionPostProcess, _super);
  75755. /**
  75756. * Creates a new instance CircleOfConfusionPostProcess
  75757. * @param name The name of the effect.
  75758. * @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.
  75759. * @param options The required width/height ratio to downsize to before computing the render pass.
  75760. * @param camera The camera to apply the render pass to.
  75761. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75762. * @param engine The engine which the post process will be applied. (default: current engine)
  75763. * @param reusable If the post process can be reused on the same frame. (default: false)
  75764. * @param textureType Type of textures used when performing the post process. (default: 0)
  75765. * @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)
  75766. */
  75767. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75768. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75769. if (blockCompilation === void 0) { blockCompilation = false; }
  75770. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75771. /**
  75772. * 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.
  75773. */
  75774. _this.lensSize = 50;
  75775. /**
  75776. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75777. */
  75778. _this.fStop = 1.4;
  75779. /**
  75780. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75781. */
  75782. _this.focusDistance = 2000;
  75783. /**
  75784. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75785. */
  75786. _this.focalLength = 50;
  75787. _this._depthTexture = null;
  75788. _this._depthTexture = depthTexture;
  75789. _this.onApplyObservable.add(function (effect) {
  75790. if (!_this._depthTexture) {
  75791. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75792. return;
  75793. }
  75794. effect.setTexture("depthSampler", _this._depthTexture);
  75795. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75796. var aperture = _this.lensSize / _this.fStop;
  75797. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75798. effect.setFloat('focusDistance', _this.focusDistance);
  75799. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75800. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75801. });
  75802. return _this;
  75803. }
  75804. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75805. /**
  75806. * 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.
  75807. */
  75808. set: function (value) {
  75809. this._depthTexture = value;
  75810. },
  75811. enumerable: true,
  75812. configurable: true
  75813. });
  75814. return CircleOfConfusionPostProcess;
  75815. }(BABYLON.PostProcess));
  75816. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75817. })(BABYLON || (BABYLON = {}));
  75818. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75819. var BABYLON;
  75820. (function (BABYLON) {
  75821. /**
  75822. * Specifies the level of max blur that should be applied when using the depth of field effect
  75823. */
  75824. var DepthOfFieldEffectBlurLevel;
  75825. (function (DepthOfFieldEffectBlurLevel) {
  75826. /**
  75827. * Subtle blur
  75828. */
  75829. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75830. /**
  75831. * Medium blur
  75832. */
  75833. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75834. /**
  75835. * Large blur
  75836. */
  75837. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75838. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75839. ;
  75840. /**
  75841. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75842. */
  75843. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75844. __extends(DepthOfFieldEffect, _super);
  75845. /**
  75846. * Creates a new instance DepthOfFieldEffect
  75847. * @param scene The scene the effect belongs to.
  75848. * @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.
  75849. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75850. * @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)
  75851. */
  75852. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75853. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75854. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75855. if (blockCompilation === void 0) { blockCompilation = false; }
  75856. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75857. return _this._effects;
  75858. }, true) || this;
  75859. /**
  75860. * Internal post processes in depth of field effect
  75861. */
  75862. _this._effects = [];
  75863. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75864. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75865. // 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)
  75866. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75867. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75868. _this._depthOfFieldBlurY = [];
  75869. _this._depthOfFieldBlurX = [];
  75870. var blurCount = 1;
  75871. var kernelSize = 15;
  75872. switch (blurLevel) {
  75873. case DepthOfFieldEffectBlurLevel.High: {
  75874. blurCount = 3;
  75875. kernelSize = 51;
  75876. break;
  75877. }
  75878. case DepthOfFieldEffectBlurLevel.Medium: {
  75879. blurCount = 2;
  75880. kernelSize = 31;
  75881. break;
  75882. }
  75883. default: {
  75884. kernelSize = 15;
  75885. blurCount = 1;
  75886. break;
  75887. }
  75888. }
  75889. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75890. var ratio = 1.0;
  75891. for (var i = 0; i < blurCount; i++) {
  75892. 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);
  75893. blurY.autoClear = false;
  75894. ratio = 0.75 / Math.pow(2, i);
  75895. 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);
  75896. blurX.autoClear = false;
  75897. _this._depthOfFieldBlurY.push(blurY);
  75898. _this._depthOfFieldBlurX.push(blurX);
  75899. }
  75900. // Set all post processes on the effect.
  75901. _this._effects = [_this._circleOfConfusion];
  75902. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75903. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75904. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75905. }
  75906. // Merge blurred images with original image based on circleOfConfusion
  75907. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75908. _this._dofMerge.autoClear = false;
  75909. _this._effects.push(_this._dofMerge);
  75910. return _this;
  75911. }
  75912. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75913. get: function () {
  75914. return this._circleOfConfusion.focalLength;
  75915. },
  75916. /**
  75917. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75918. */
  75919. set: function (value) {
  75920. this._circleOfConfusion.focalLength = value;
  75921. },
  75922. enumerable: true,
  75923. configurable: true
  75924. });
  75925. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75926. get: function () {
  75927. return this._circleOfConfusion.fStop;
  75928. },
  75929. /**
  75930. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75931. */
  75932. set: function (value) {
  75933. this._circleOfConfusion.fStop = value;
  75934. },
  75935. enumerable: true,
  75936. configurable: true
  75937. });
  75938. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75939. get: function () {
  75940. return this._circleOfConfusion.focusDistance;
  75941. },
  75942. /**
  75943. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75944. */
  75945. set: function (value) {
  75946. this._circleOfConfusion.focusDistance = value;
  75947. },
  75948. enumerable: true,
  75949. configurable: true
  75950. });
  75951. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75952. get: function () {
  75953. return this._circleOfConfusion.lensSize;
  75954. },
  75955. /**
  75956. * 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.
  75957. */
  75958. set: function (value) {
  75959. this._circleOfConfusion.lensSize = value;
  75960. },
  75961. enumerable: true,
  75962. configurable: true
  75963. });
  75964. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75965. /**
  75966. * 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.
  75967. */
  75968. set: function (value) {
  75969. this._circleOfConfusion.depthTexture = value;
  75970. },
  75971. enumerable: true,
  75972. configurable: true
  75973. });
  75974. /**
  75975. * Disposes each of the internal effects for a given camera.
  75976. * @param camera The camera to dispose the effect on.
  75977. */
  75978. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75979. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75980. this._effects[effectIndex].dispose(camera);
  75981. }
  75982. };
  75983. /**
  75984. * Internal
  75985. */
  75986. DepthOfFieldEffect.prototype._updateEffects = function () {
  75987. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75988. this._effects[effectIndex].updateEffect();
  75989. }
  75990. };
  75991. /**
  75992. * Internal
  75993. * @returns if all the contained post processes are ready.
  75994. */
  75995. DepthOfFieldEffect.prototype._isReady = function () {
  75996. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75997. if (!this._effects[effectIndex].isReady()) {
  75998. return false;
  75999. }
  76000. }
  76001. return true;
  76002. };
  76003. return DepthOfFieldEffect;
  76004. }(BABYLON.PostProcessRenderEffect));
  76005. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76006. })(BABYLON || (BABYLON = {}));
  76007. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76008. var BABYLON;
  76009. (function (BABYLON) {
  76010. /**
  76011. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76012. */
  76013. var BloomMergePostProcess = /** @class */ (function (_super) {
  76014. __extends(BloomMergePostProcess, _super);
  76015. /**
  76016. * Creates a new instance of @see BloomMergePostProcess
  76017. * @param name The name of the effect.
  76018. * @param originalFromInput Post process which's input will be used for the merge.
  76019. * @param blurred Blurred highlights post process which's output will be used.
  76020. * @param weight Weight of the bloom to be added to the original input.
  76021. * @param options The required width/height ratio to downsize to before computing the render pass.
  76022. * @param camera The camera to apply the render pass to.
  76023. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76024. * @param engine The engine which the post process will be applied. (default: current engine)
  76025. * @param reusable If the post process can be reused on the same frame. (default: false)
  76026. * @param textureType Type of textures used when performing the post process. (default: 0)
  76027. * @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)
  76028. */
  76029. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76030. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76031. if (blockCompilation === void 0) { blockCompilation = false; }
  76032. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76033. _this.weight = weight;
  76034. _this.onApplyObservable.add(function (effect) {
  76035. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76036. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76037. effect.setFloat("bloomWeight", _this.weight);
  76038. });
  76039. if (!blockCompilation) {
  76040. _this.updateEffect();
  76041. }
  76042. return _this;
  76043. }
  76044. return BloomMergePostProcess;
  76045. }(BABYLON.PostProcess));
  76046. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76047. })(BABYLON || (BABYLON = {}));
  76048. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76049. var BABYLON;
  76050. (function (BABYLON) {
  76051. /**
  76052. * 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.
  76053. */
  76054. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76055. __extends(ExtractHighlightsPostProcess, _super);
  76056. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76057. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76058. if (blockCompilation === void 0) { blockCompilation = false; }
  76059. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76060. /**
  76061. * The luminance threshold, pixels below this value will be set to black.
  76062. */
  76063. _this.threshold = 0.9;
  76064. /**
  76065. * Internal
  76066. */
  76067. _this._exposure = 1;
  76068. /**
  76069. * Post process which has the input texture to be used when performing highlight extraction
  76070. */
  76071. _this._inputPostProcess = null;
  76072. _this.onApplyObservable.add(function (effect) {
  76073. if (_this._inputPostProcess) {
  76074. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76075. }
  76076. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76077. effect.setFloat('exposure', _this._exposure);
  76078. });
  76079. return _this;
  76080. }
  76081. return ExtractHighlightsPostProcess;
  76082. }(BABYLON.PostProcess));
  76083. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76084. })(BABYLON || (BABYLON = {}));
  76085. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76086. var BABYLON;
  76087. (function (BABYLON) {
  76088. /**
  76089. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76090. */
  76091. var BloomEffect = /** @class */ (function (_super) {
  76092. __extends(BloomEffect, _super);
  76093. /**
  76094. * Creates a new instance of @see BloomEffect
  76095. * @param scene The scene the effect belongs to.
  76096. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76097. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76098. * @param bloomWeight The the strength of bloom.
  76099. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76100. * @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)
  76101. */
  76102. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76103. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76104. if (blockCompilation === void 0) { blockCompilation = false; }
  76105. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76106. return _this._effects;
  76107. }, true) || this;
  76108. _this.bloomScale = bloomScale;
  76109. /**
  76110. * Internal
  76111. */
  76112. _this._effects = [];
  76113. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76114. _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);
  76115. _this._blurX.alwaysForcePOT = true;
  76116. _this._blurX.autoClear = false;
  76117. _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);
  76118. _this._blurY.alwaysForcePOT = true;
  76119. _this._blurY.autoClear = false;
  76120. _this.kernel = bloomKernel;
  76121. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76122. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76123. _this._merge.autoClear = false;
  76124. _this._effects.push(_this._merge);
  76125. return _this;
  76126. }
  76127. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76128. /**
  76129. * The luminance threshold to find bright areas of the image to bloom.
  76130. */
  76131. get: function () {
  76132. return this._downscale.threshold;
  76133. },
  76134. set: function (value) {
  76135. this._downscale.threshold = value;
  76136. },
  76137. enumerable: true,
  76138. configurable: true
  76139. });
  76140. Object.defineProperty(BloomEffect.prototype, "weight", {
  76141. /**
  76142. * The strength of the bloom.
  76143. */
  76144. get: function () {
  76145. return this._merge.weight;
  76146. },
  76147. set: function (value) {
  76148. this._merge.weight = value;
  76149. },
  76150. enumerable: true,
  76151. configurable: true
  76152. });
  76153. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76154. /**
  76155. * Specifies the size of the bloom blur kernel, relative to the final output size
  76156. */
  76157. get: function () {
  76158. return this._blurX.kernel / this.bloomScale;
  76159. },
  76160. set: function (value) {
  76161. this._blurX.kernel = value * this.bloomScale;
  76162. this._blurY.kernel = value * this.bloomScale;
  76163. },
  76164. enumerable: true,
  76165. configurable: true
  76166. });
  76167. /**
  76168. * Disposes each of the internal effects for a given camera.
  76169. * @param camera The camera to dispose the effect on.
  76170. */
  76171. BloomEffect.prototype.disposeEffects = function (camera) {
  76172. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76173. this._effects[effectIndex].dispose(camera);
  76174. }
  76175. };
  76176. /**
  76177. * Internal
  76178. */
  76179. BloomEffect.prototype._updateEffects = function () {
  76180. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76181. this._effects[effectIndex].updateEffect();
  76182. }
  76183. };
  76184. /**
  76185. * Internal
  76186. * @returns if all the contained post processes are ready.
  76187. */
  76188. BloomEffect.prototype._isReady = function () {
  76189. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76190. if (!this._effects[effectIndex].isReady()) {
  76191. return false;
  76192. }
  76193. }
  76194. return true;
  76195. };
  76196. return BloomEffect;
  76197. }(BABYLON.PostProcessRenderEffect));
  76198. BABYLON.BloomEffect = BloomEffect;
  76199. })(BABYLON || (BABYLON = {}));
  76200. //# sourceMappingURL=babylon.bloomEffect.js.map
  76201. var BABYLON;
  76202. (function (BABYLON) {
  76203. /**
  76204. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76205. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76206. */
  76207. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76208. __extends(DefaultRenderingPipeline, _super);
  76209. /**
  76210. * @constructor
  76211. * @param {string} name - The rendering pipeline name (default: "")
  76212. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76213. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76214. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76215. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76216. */
  76217. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76218. if (name === void 0) { name = ""; }
  76219. if (hdr === void 0) { hdr = true; }
  76220. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76221. if (automaticBuild === void 0) { automaticBuild = true; }
  76222. var _this = _super.call(this, scene.getEngine(), name) || this;
  76223. _this._originalCameras = [];
  76224. /**
  76225. * ID of the sharpen post process,
  76226. */
  76227. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76228. /**
  76229. * ID of the image processing post process;
  76230. */
  76231. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76232. /**
  76233. * ID of the Fast Approximate Anti-Aliasing post process;
  76234. */
  76235. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76236. /**
  76237. * ID of the chromatic aberration post process,
  76238. */
  76239. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76240. /**
  76241. * ID of the grain post process
  76242. */
  76243. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76244. /**
  76245. * Glow post process which adds a glow to emmisive areas of the image
  76246. */
  76247. _this._glowLayer = null;
  76248. /**
  76249. * Animations which can be used to tweak settings over a period of time
  76250. */
  76251. _this.animations = [];
  76252. _this._imageProcessingConfigurationObserver = null;
  76253. // Values
  76254. _this._sharpenEnabled = false;
  76255. _this._bloomEnabled = false;
  76256. _this._depthOfFieldEnabled = false;
  76257. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76258. _this._fxaaEnabled = false;
  76259. _this._imageProcessingEnabled = true;
  76260. _this._bloomScale = 0.5;
  76261. _this._chromaticAberrationEnabled = false;
  76262. _this._grainEnabled = false;
  76263. _this._buildAllowed = true;
  76264. _this._resizeObserver = null;
  76265. _this._hardwareScaleLevel = 1.0;
  76266. _this._bloomKernel = 64;
  76267. /**
  76268. * Specifies the weight of the bloom in the final rendering
  76269. */
  76270. _this._bloomWeight = 0.15;
  76271. /**
  76272. * Specifies the luma threshold for the area that will be blurred by the bloom
  76273. */
  76274. _this._bloomThreshold = 0.9;
  76275. _this._samples = 1;
  76276. _this._hasCleared = false;
  76277. _this._prevPostProcess = null;
  76278. _this._prevPrevPostProcess = null;
  76279. _this._cameras = cameras || scene.cameras;
  76280. _this._originalCameras = _this._cameras.slice();
  76281. _this._buildAllowed = automaticBuild;
  76282. // Initialize
  76283. _this._scene = scene;
  76284. var caps = _this._scene.getEngine().getCaps();
  76285. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76286. // Misc
  76287. if (_this._hdr) {
  76288. if (caps.textureHalfFloatRender) {
  76289. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76290. }
  76291. else if (caps.textureFloatRender) {
  76292. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76293. }
  76294. }
  76295. else {
  76296. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76297. }
  76298. // Attach
  76299. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76300. var engine = _this._scene.getEngine();
  76301. // Create post processes before hand so they can be modified before enabled.
  76302. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76303. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76304. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76305. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76306. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76307. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76308. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76309. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76310. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76311. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76312. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76313. _this.bloomKernel = _this.bloomKernel;
  76314. });
  76315. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76316. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76317. });
  76318. _this._buildPipeline();
  76319. return _this;
  76320. }
  76321. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76322. get: function () {
  76323. return this._sharpenEnabled;
  76324. },
  76325. /**
  76326. * Enable or disable the sharpen process from the pipeline
  76327. */
  76328. set: function (enabled) {
  76329. if (this._sharpenEnabled === enabled) {
  76330. return;
  76331. }
  76332. this._sharpenEnabled = enabled;
  76333. this._buildPipeline();
  76334. },
  76335. enumerable: true,
  76336. configurable: true
  76337. });
  76338. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76339. /**
  76340. * Specifies the size of the bloom blur kernel, relative to the final output size
  76341. */
  76342. get: function () {
  76343. return this._bloomKernel;
  76344. },
  76345. set: function (value) {
  76346. this._bloomKernel = value;
  76347. this.bloom.kernel = value / this._hardwareScaleLevel;
  76348. },
  76349. enumerable: true,
  76350. configurable: true
  76351. });
  76352. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76353. get: function () {
  76354. return this._bloomWeight;
  76355. },
  76356. /**
  76357. * The strength of the bloom.
  76358. */
  76359. set: function (value) {
  76360. if (this._bloomWeight === value) {
  76361. return;
  76362. }
  76363. this.bloom.weight = value;
  76364. this._bloomWeight = value;
  76365. },
  76366. enumerable: true,
  76367. configurable: true
  76368. });
  76369. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76370. get: function () {
  76371. return this._bloomThreshold;
  76372. },
  76373. /**
  76374. * The strength of the bloom.
  76375. */
  76376. set: function (value) {
  76377. if (this._bloomThreshold === value) {
  76378. return;
  76379. }
  76380. this.bloom.threshold = value;
  76381. this._bloomThreshold = value;
  76382. },
  76383. enumerable: true,
  76384. configurable: true
  76385. });
  76386. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76387. get: function () {
  76388. return this._bloomScale;
  76389. },
  76390. /**
  76391. * The scale of the bloom, lower value will provide better performance.
  76392. */
  76393. set: function (value) {
  76394. if (this._bloomScale === value) {
  76395. return;
  76396. }
  76397. this._bloomScale = value;
  76398. // recreate bloom and dispose old as this setting is not dynamic
  76399. this._rebuildBloom();
  76400. this._buildPipeline();
  76401. },
  76402. enumerable: true,
  76403. configurable: true
  76404. });
  76405. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76406. get: function () {
  76407. return this._bloomEnabled;
  76408. },
  76409. /**
  76410. * Enable or disable the bloom from the pipeline
  76411. */
  76412. set: function (enabled) {
  76413. if (this._bloomEnabled === enabled) {
  76414. return;
  76415. }
  76416. this._bloomEnabled = enabled;
  76417. this._buildPipeline();
  76418. },
  76419. enumerable: true,
  76420. configurable: true
  76421. });
  76422. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76423. // recreate bloom and dispose old as this setting is not dynamic
  76424. var oldBloom = this.bloom;
  76425. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76426. this.bloom.threshold = oldBloom.threshold;
  76427. for (var i = 0; i < this._cameras.length; i++) {
  76428. oldBloom.disposeEffects(this._cameras[i]);
  76429. }
  76430. };
  76431. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76432. /**
  76433. * If the depth of field is enabled.
  76434. */
  76435. get: function () {
  76436. return this._depthOfFieldEnabled;
  76437. },
  76438. set: function (enabled) {
  76439. if (this._depthOfFieldEnabled === enabled) {
  76440. return;
  76441. }
  76442. this._depthOfFieldEnabled = enabled;
  76443. this._buildPipeline();
  76444. },
  76445. enumerable: true,
  76446. configurable: true
  76447. });
  76448. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76449. /**
  76450. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76451. */
  76452. get: function () {
  76453. return this._depthOfFieldBlurLevel;
  76454. },
  76455. set: function (value) {
  76456. if (this._depthOfFieldBlurLevel === value) {
  76457. return;
  76458. }
  76459. this._depthOfFieldBlurLevel = value;
  76460. // recreate dof and dispose old as this setting is not dynamic
  76461. var oldDof = this.depthOfField;
  76462. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76463. this.depthOfField.focalLength = oldDof.focalLength;
  76464. this.depthOfField.focusDistance = oldDof.focusDistance;
  76465. this.depthOfField.fStop = oldDof.fStop;
  76466. this.depthOfField.lensSize = oldDof.lensSize;
  76467. for (var i = 0; i < this._cameras.length; i++) {
  76468. oldDof.disposeEffects(this._cameras[i]);
  76469. }
  76470. this._buildPipeline();
  76471. },
  76472. enumerable: true,
  76473. configurable: true
  76474. });
  76475. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76476. get: function () {
  76477. return this._fxaaEnabled;
  76478. },
  76479. /**
  76480. * If the anti aliasing is enabled.
  76481. */
  76482. set: function (enabled) {
  76483. if (this._fxaaEnabled === enabled) {
  76484. return;
  76485. }
  76486. this._fxaaEnabled = enabled;
  76487. this._buildPipeline();
  76488. },
  76489. enumerable: true,
  76490. configurable: true
  76491. });
  76492. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76493. get: function () {
  76494. return this._samples;
  76495. },
  76496. /**
  76497. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76498. */
  76499. set: function (sampleCount) {
  76500. if (this._samples === sampleCount) {
  76501. return;
  76502. }
  76503. this._samples = sampleCount;
  76504. this._buildPipeline();
  76505. },
  76506. enumerable: true,
  76507. configurable: true
  76508. });
  76509. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76510. get: function () {
  76511. return this._imageProcessingEnabled;
  76512. },
  76513. /**
  76514. * If image processing is enabled.
  76515. */
  76516. set: function (enabled) {
  76517. if (this._imageProcessingEnabled === enabled) {
  76518. return;
  76519. }
  76520. this._imageProcessingEnabled = enabled;
  76521. this._buildPipeline();
  76522. },
  76523. enumerable: true,
  76524. configurable: true
  76525. });
  76526. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76527. get: function () {
  76528. return this._glowLayer == null;
  76529. },
  76530. /**
  76531. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76532. */
  76533. set: function (enabled) {
  76534. if (enabled && !this._glowLayer) {
  76535. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76536. }
  76537. else if (!enabled && this._glowLayer) {
  76538. this._glowLayer.dispose();
  76539. this._glowLayer = null;
  76540. }
  76541. },
  76542. enumerable: true,
  76543. configurable: true
  76544. });
  76545. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76546. get: function () {
  76547. return this._chromaticAberrationEnabled;
  76548. },
  76549. /**
  76550. * Enable or disable the chromaticAberration process from the pipeline
  76551. */
  76552. set: function (enabled) {
  76553. if (this._chromaticAberrationEnabled === enabled) {
  76554. return;
  76555. }
  76556. this._chromaticAberrationEnabled = enabled;
  76557. this._buildPipeline();
  76558. },
  76559. enumerable: true,
  76560. configurable: true
  76561. });
  76562. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76563. get: function () {
  76564. return this._grainEnabled;
  76565. },
  76566. /**
  76567. * Enable or disable the grain process from the pipeline
  76568. */
  76569. set: function (enabled) {
  76570. if (this._grainEnabled === enabled) {
  76571. return;
  76572. }
  76573. this._grainEnabled = enabled;
  76574. this._buildPipeline();
  76575. },
  76576. enumerable: true,
  76577. configurable: true
  76578. });
  76579. /**
  76580. * Force the compilation of the entire pipeline.
  76581. */
  76582. DefaultRenderingPipeline.prototype.prepare = function () {
  76583. var previousState = this._buildAllowed;
  76584. this._buildAllowed = true;
  76585. this._buildPipeline();
  76586. this._buildAllowed = previousState;
  76587. };
  76588. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76589. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76590. if (this._hasCleared) {
  76591. postProcess.autoClear = false;
  76592. }
  76593. else {
  76594. postProcess.autoClear = true;
  76595. this._scene.autoClear = false;
  76596. this._hasCleared = true;
  76597. }
  76598. if (!skipTextureSharing) {
  76599. if (this._prevPrevPostProcess) {
  76600. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76601. }
  76602. else {
  76603. postProcess.useOwnOutput();
  76604. }
  76605. if (this._prevPostProcess) {
  76606. this._prevPrevPostProcess = this._prevPostProcess;
  76607. }
  76608. this._prevPostProcess = postProcess;
  76609. }
  76610. };
  76611. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76612. var _this = this;
  76613. if (!this._buildAllowed) {
  76614. return;
  76615. }
  76616. this._scene.autoClear = true;
  76617. var engine = this._scene.getEngine();
  76618. this._disposePostProcesses();
  76619. if (this._cameras !== null) {
  76620. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76621. // get back cameras to be used to reattach pipeline
  76622. this._cameras = this._originalCameras.slice();
  76623. }
  76624. this._reset();
  76625. this._prevPostProcess = null;
  76626. this._prevPrevPostProcess = null;
  76627. this._hasCleared = false;
  76628. if (this.depthOfFieldEnabled) {
  76629. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76630. this.depthOfField.depthTexture = depthTexture;
  76631. if (!this.depthOfField._isReady()) {
  76632. this.depthOfField._updateEffects();
  76633. }
  76634. this.addEffect(this.depthOfField);
  76635. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76636. }
  76637. if (this.bloomEnabled) {
  76638. if (!this.bloom._isReady()) {
  76639. this.bloom._updateEffects();
  76640. }
  76641. this.addEffect(this.bloom);
  76642. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76643. }
  76644. if (this._imageProcessingEnabled) {
  76645. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76646. if (this._hdr) {
  76647. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76648. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76649. }
  76650. else {
  76651. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76652. }
  76653. }
  76654. if (this.sharpenEnabled) {
  76655. if (!this.sharpen.isReady()) {
  76656. this.sharpen.updateEffect();
  76657. }
  76658. this.addEffect(this._sharpenEffect);
  76659. this._setAutoClearAndTextureSharing(this.sharpen);
  76660. }
  76661. if (this.grainEnabled) {
  76662. if (!this.grain.isReady()) {
  76663. this.grain.updateEffect();
  76664. }
  76665. this.addEffect(this._grainEffect);
  76666. this._setAutoClearAndTextureSharing(this.grain);
  76667. }
  76668. if (this.chromaticAberrationEnabled) {
  76669. if (!this.chromaticAberration.isReady()) {
  76670. this.chromaticAberration.updateEffect();
  76671. }
  76672. this.addEffect(this._chromaticAberrationEffect);
  76673. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76674. }
  76675. if (this.fxaaEnabled) {
  76676. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76677. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76678. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76679. }
  76680. if (this._cameras !== null) {
  76681. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76682. }
  76683. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76684. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76685. }
  76686. };
  76687. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76688. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76689. for (var i = 0; i < this._cameras.length; i++) {
  76690. var camera = this._cameras[i];
  76691. if (this.imageProcessing) {
  76692. this.imageProcessing.dispose(camera);
  76693. }
  76694. if (this.fxaa) {
  76695. this.fxaa.dispose(camera);
  76696. }
  76697. // These are created in the constructor and should not be disposed on every pipeline change
  76698. if (disposeNonRecreated) {
  76699. if (this.sharpen) {
  76700. this.sharpen.dispose(camera);
  76701. }
  76702. if (this.depthOfField) {
  76703. this.depthOfField.disposeEffects(camera);
  76704. }
  76705. if (this.bloom) {
  76706. this.bloom.disposeEffects(camera);
  76707. }
  76708. if (this.chromaticAberration) {
  76709. this.chromaticAberration.dispose(camera);
  76710. }
  76711. if (this.grain) {
  76712. this.grain.dispose(camera);
  76713. }
  76714. if (this._glowLayer) {
  76715. this._glowLayer.dispose();
  76716. }
  76717. }
  76718. }
  76719. this.imageProcessing = null;
  76720. this.fxaa = null;
  76721. if (disposeNonRecreated) {
  76722. this.sharpen = null;
  76723. this._sharpenEffect = null;
  76724. this.depthOfField = null;
  76725. this.bloom = null;
  76726. this.chromaticAberration = null;
  76727. this._chromaticAberrationEffect = null;
  76728. this.grain = null;
  76729. this._grainEffect = null;
  76730. this._glowLayer = null;
  76731. }
  76732. };
  76733. /**
  76734. * Dispose of the pipeline and stop all post processes
  76735. */
  76736. DefaultRenderingPipeline.prototype.dispose = function () {
  76737. this._disposePostProcesses(true);
  76738. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76739. this._scene.autoClear = true;
  76740. if (this._resizeObserver) {
  76741. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76742. this._resizeObserver = null;
  76743. }
  76744. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76745. _super.prototype.dispose.call(this);
  76746. };
  76747. /**
  76748. * Serialize the rendering pipeline (Used when exporting)
  76749. * @returns the serialized object
  76750. */
  76751. DefaultRenderingPipeline.prototype.serialize = function () {
  76752. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76753. serializationObject.customType = "DefaultRenderingPipeline";
  76754. return serializationObject;
  76755. };
  76756. /**
  76757. * Parse the serialized pipeline
  76758. * @param source Source pipeline.
  76759. * @param scene The scene to load the pipeline to.
  76760. * @param rootUrl The URL of the serialized pipeline.
  76761. * @returns An instantiated pipeline from the serialized object.
  76762. */
  76763. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76764. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76765. };
  76766. __decorate([
  76767. BABYLON.serialize()
  76768. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76769. __decorate([
  76770. BABYLON.serialize()
  76771. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76772. __decorate([
  76773. BABYLON.serialize()
  76774. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76775. __decorate([
  76776. BABYLON.serialize()
  76777. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76778. __decorate([
  76779. BABYLON.serialize()
  76780. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76781. __decorate([
  76782. BABYLON.serialize()
  76783. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76784. __decorate([
  76785. BABYLON.serialize()
  76786. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76787. __decorate([
  76788. BABYLON.serialize()
  76789. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76790. __decorate([
  76791. BABYLON.serialize()
  76792. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76793. __decorate([
  76794. BABYLON.serialize()
  76795. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76796. __decorate([
  76797. BABYLON.serialize()
  76798. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76799. __decorate([
  76800. BABYLON.serialize()
  76801. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76802. __decorate([
  76803. BABYLON.serialize()
  76804. ], DefaultRenderingPipeline.prototype, "samples", null);
  76805. __decorate([
  76806. BABYLON.serialize()
  76807. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76808. __decorate([
  76809. BABYLON.serialize()
  76810. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76811. __decorate([
  76812. BABYLON.serialize()
  76813. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76814. __decorate([
  76815. BABYLON.serialize()
  76816. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76817. return DefaultRenderingPipeline;
  76818. }(BABYLON.PostProcessRenderPipeline));
  76819. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76820. })(BABYLON || (BABYLON = {}));
  76821. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76822. var BABYLON;
  76823. (function (BABYLON) {
  76824. /**
  76825. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76826. */
  76827. var GeometryBufferRenderer = /** @class */ (function () {
  76828. /**
  76829. * Creates a new G Buffer for the scene
  76830. * @param scene The scene the buffer belongs to
  76831. * @param ratio How big is the buffer related to the main canvas.
  76832. */
  76833. function GeometryBufferRenderer(scene, ratio) {
  76834. if (ratio === void 0) { ratio = 1; }
  76835. this._enablePosition = false;
  76836. this._scene = scene;
  76837. this._ratio = ratio;
  76838. // Render target
  76839. this._createRenderTargets();
  76840. }
  76841. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76842. /**
  76843. * Set the render list (meshes to be rendered) used in the G buffer.
  76844. */
  76845. set: function (meshes) {
  76846. this._multiRenderTarget.renderList = meshes;
  76847. },
  76848. enumerable: true,
  76849. configurable: true
  76850. });
  76851. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76852. /**
  76853. * Gets wether or not G buffer are supported by the running hardware.
  76854. * This requires draw buffer supports
  76855. */
  76856. get: function () {
  76857. return this._multiRenderTarget.isSupported;
  76858. },
  76859. enumerable: true,
  76860. configurable: true
  76861. });
  76862. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76863. /**
  76864. * Gets wether or not position are enabled for the G buffer.
  76865. */
  76866. get: function () {
  76867. return this._enablePosition;
  76868. },
  76869. /**
  76870. * Sets wether or not position are enabled for the G buffer.
  76871. */
  76872. set: function (enable) {
  76873. this._enablePosition = enable;
  76874. this.dispose();
  76875. this._createRenderTargets();
  76876. },
  76877. enumerable: true,
  76878. configurable: true
  76879. });
  76880. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76881. /**
  76882. * Gets the scene associated with the buffer.
  76883. */
  76884. get: function () {
  76885. return this._scene;
  76886. },
  76887. enumerable: true,
  76888. configurable: true
  76889. });
  76890. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76891. /**
  76892. * Gets the ratio used by the buffer during its creation.
  76893. * How big is the buffer related to the main canvas.
  76894. */
  76895. get: function () {
  76896. return this._ratio;
  76897. },
  76898. enumerable: true,
  76899. configurable: true
  76900. });
  76901. /**
  76902. * Checks wether everything is ready to render a submesh to the G buffer.
  76903. * @param subMesh the submesh to check readiness for
  76904. * @param useInstances is the mesh drawn using instance or not
  76905. * @returns true if ready otherwise false
  76906. */
  76907. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76908. var material = subMesh.getMaterial();
  76909. if (material && material.disableDepthWrite) {
  76910. return false;
  76911. }
  76912. var defines = [];
  76913. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76914. var mesh = subMesh.getMesh();
  76915. // Alpha test
  76916. if (material && material.needAlphaTesting()) {
  76917. defines.push("#define ALPHATEST");
  76918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76919. attribs.push(BABYLON.VertexBuffer.UVKind);
  76920. defines.push("#define UV1");
  76921. }
  76922. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76923. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76924. defines.push("#define UV2");
  76925. }
  76926. }
  76927. // Buffers
  76928. if (this._enablePosition) {
  76929. defines.push("#define POSITION");
  76930. }
  76931. // Bones
  76932. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76933. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76934. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76935. if (mesh.numBoneInfluencers > 4) {
  76936. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76937. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76938. }
  76939. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76940. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76941. }
  76942. else {
  76943. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76944. }
  76945. // Instances
  76946. if (useInstances) {
  76947. defines.push("#define INSTANCES");
  76948. attribs.push("world0");
  76949. attribs.push("world1");
  76950. attribs.push("world2");
  76951. attribs.push("world3");
  76952. }
  76953. // Get correct effect
  76954. var join = defines.join("\n");
  76955. if (this._cachedDefines !== join) {
  76956. this._cachedDefines = join;
  76957. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76958. }
  76959. return this._effect.isReady();
  76960. };
  76961. /**
  76962. * Gets the current underlying G Buffer.
  76963. * @returns the buffer
  76964. */
  76965. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76966. return this._multiRenderTarget;
  76967. };
  76968. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76969. /**
  76970. * Gets the number of samples used to render the buffer (anti aliasing).
  76971. */
  76972. get: function () {
  76973. return this._multiRenderTarget.samples;
  76974. },
  76975. /**
  76976. * Sets the number of samples used to render the buffer (anti aliasing).
  76977. */
  76978. set: function (value) {
  76979. this._multiRenderTarget.samples = value;
  76980. },
  76981. enumerable: true,
  76982. configurable: true
  76983. });
  76984. /**
  76985. * Disposes the renderer and frees up associated resources.
  76986. */
  76987. GeometryBufferRenderer.prototype.dispose = function () {
  76988. this.getGBuffer().dispose();
  76989. };
  76990. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76991. var _this = this;
  76992. var engine = this._scene.getEngine();
  76993. var count = this._enablePosition ? 3 : 2;
  76994. 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 });
  76995. if (!this.isSupported) {
  76996. return;
  76997. }
  76998. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76999. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77000. this._multiRenderTarget.refreshRate = 1;
  77001. this._multiRenderTarget.renderParticles = false;
  77002. this._multiRenderTarget.renderList = null;
  77003. // set default depth value to 1.0 (far away)
  77004. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77005. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77006. });
  77007. // Custom render function
  77008. var renderSubMesh = function (subMesh) {
  77009. var mesh = subMesh.getRenderingMesh();
  77010. var scene = _this._scene;
  77011. var engine = scene.getEngine();
  77012. var material = subMesh.getMaterial();
  77013. if (!material) {
  77014. return;
  77015. }
  77016. // Culling
  77017. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77018. // Managing instances
  77019. var batch = mesh._getInstancesRenderList(subMesh._id);
  77020. if (batch.mustReturn) {
  77021. return;
  77022. }
  77023. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77024. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77025. engine.enableEffect(_this._effect);
  77026. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77027. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77028. _this._effect.setMatrix("view", scene.getViewMatrix());
  77029. // Alpha test
  77030. if (material && material.needAlphaTesting()) {
  77031. var alphaTexture = material.getAlphaTestTexture();
  77032. if (alphaTexture) {
  77033. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77034. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77035. }
  77036. }
  77037. // Bones
  77038. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77039. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77040. }
  77041. // Draw
  77042. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77043. }
  77044. };
  77045. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77046. var index;
  77047. if (depthOnlySubMeshes.length) {
  77048. engine.setColorWrite(false);
  77049. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77050. renderSubMesh(depthOnlySubMeshes.data[index]);
  77051. }
  77052. engine.setColorWrite(true);
  77053. }
  77054. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77055. renderSubMesh(opaqueSubMeshes.data[index]);
  77056. }
  77057. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77058. renderSubMesh(alphaTestSubMeshes.data[index]);
  77059. }
  77060. };
  77061. };
  77062. return GeometryBufferRenderer;
  77063. }());
  77064. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77065. })(BABYLON || (BABYLON = {}));
  77066. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77067. var BABYLON;
  77068. (function (BABYLON) {
  77069. var RefractionPostProcess = /** @class */ (function (_super) {
  77070. __extends(RefractionPostProcess, _super);
  77071. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77072. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77073. _this.color = color;
  77074. _this.depth = depth;
  77075. _this.colorLevel = colorLevel;
  77076. _this._ownRefractionTexture = true;
  77077. _this.onActivateObservable.add(function (cam) {
  77078. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77079. });
  77080. _this.onApplyObservable.add(function (effect) {
  77081. effect.setColor3("baseColor", _this.color);
  77082. effect.setFloat("depth", _this.depth);
  77083. effect.setFloat("colorLevel", _this.colorLevel);
  77084. effect.setTexture("refractionSampler", _this._refTexture);
  77085. });
  77086. return _this;
  77087. }
  77088. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77089. /**
  77090. * Gets or sets the refraction texture
  77091. * Please note that you are responsible for disposing the texture if you set it manually
  77092. */
  77093. get: function () {
  77094. return this._refTexture;
  77095. },
  77096. set: function (value) {
  77097. if (this._refTexture && this._ownRefractionTexture) {
  77098. this._refTexture.dispose();
  77099. }
  77100. this._refTexture = value;
  77101. this._ownRefractionTexture = false;
  77102. },
  77103. enumerable: true,
  77104. configurable: true
  77105. });
  77106. // Methods
  77107. RefractionPostProcess.prototype.dispose = function (camera) {
  77108. if (this._refTexture && this._ownRefractionTexture) {
  77109. this._refTexture.dispose();
  77110. this._refTexture = null;
  77111. }
  77112. _super.prototype.dispose.call(this, camera);
  77113. };
  77114. return RefractionPostProcess;
  77115. }(BABYLON.PostProcess));
  77116. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77117. })(BABYLON || (BABYLON = {}));
  77118. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77119. var BABYLON;
  77120. (function (BABYLON) {
  77121. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77122. __extends(BlackAndWhitePostProcess, _super);
  77123. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77124. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77125. _this.degree = 1;
  77126. _this.onApplyObservable.add(function (effect) {
  77127. effect.setFloat("degree", _this.degree);
  77128. });
  77129. return _this;
  77130. }
  77131. return BlackAndWhitePostProcess;
  77132. }(BABYLON.PostProcess));
  77133. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77134. })(BABYLON || (BABYLON = {}));
  77135. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77136. var BABYLON;
  77137. (function (BABYLON) {
  77138. /**
  77139. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77140. * input texture to perform effects such as edge detection or sharpening
  77141. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77142. */
  77143. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77144. __extends(ConvolutionPostProcess, _super);
  77145. /**
  77146. * Creates a new instance ConvolutionPostProcess
  77147. * @param name The name of the effect.
  77148. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77149. * @param options The required width/height ratio to downsize to before computing the render pass.
  77150. * @param camera The camera to apply the render pass to.
  77151. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77152. * @param engine The engine which the post process will be applied. (default: current engine)
  77153. * @param reusable If the post process can be reused on the same frame. (default: false)
  77154. * @param textureType Type of textures used when performing the post process. (default: 0)
  77155. */
  77156. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77157. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77158. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77159. _this.kernel = kernel;
  77160. _this.onApply = function (effect) {
  77161. effect.setFloat2("screenSize", _this.width, _this.height);
  77162. effect.setArray("kernel", _this.kernel);
  77163. };
  77164. return _this;
  77165. }
  77166. // Statics
  77167. /**
  77168. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77169. */
  77170. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77171. /**
  77172. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77173. */
  77174. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77175. /**
  77176. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77177. */
  77178. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77179. /**
  77180. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77181. */
  77182. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77183. /**
  77184. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77185. */
  77186. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77187. /**
  77188. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77189. */
  77190. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77191. return ConvolutionPostProcess;
  77192. }(BABYLON.PostProcess));
  77193. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77194. })(BABYLON || (BABYLON = {}));
  77195. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77196. var BABYLON;
  77197. (function (BABYLON) {
  77198. var FilterPostProcess = /** @class */ (function (_super) {
  77199. __extends(FilterPostProcess, _super);
  77200. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77201. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77202. _this.kernelMatrix = kernelMatrix;
  77203. _this.onApply = function (effect) {
  77204. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77205. };
  77206. return _this;
  77207. }
  77208. return FilterPostProcess;
  77209. }(BABYLON.PostProcess));
  77210. BABYLON.FilterPostProcess = FilterPostProcess;
  77211. })(BABYLON || (BABYLON = {}));
  77212. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77213. var BABYLON;
  77214. (function (BABYLON) {
  77215. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77216. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77217. __extends(VolumetricLightScatteringPostProcess, _super);
  77218. /**
  77219. * @constructor
  77220. * @param {string} name - The post-process name
  77221. * @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)
  77222. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77223. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77224. * @param {number} samples - The post-process quality, default 100
  77225. * @param {number} samplingMode - The post-process filtering mode
  77226. * @param {BABYLON.Engine} engine - The babylon engine
  77227. * @param {boolean} reusable - If the post-process is reusable
  77228. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77229. */
  77230. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77231. if (samples === void 0) { samples = 100; }
  77232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77233. 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;
  77234. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77235. /**
  77236. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77237. */
  77238. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77239. /**
  77240. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77241. */
  77242. _this.useCustomMeshPosition = false;
  77243. /**
  77244. * If the post-process should inverse the light scattering direction
  77245. */
  77246. _this.invert = true;
  77247. /**
  77248. * Array containing the excluded meshes not rendered in the internal pass
  77249. */
  77250. _this.excludedMeshes = new Array();
  77251. /**
  77252. * Controls the overall intensity of the post-process
  77253. */
  77254. _this.exposure = 0.3;
  77255. /**
  77256. * Dissipates each sample's contribution in range [0, 1]
  77257. */
  77258. _this.decay = 0.96815;
  77259. /**
  77260. * Controls the overall intensity of each sample
  77261. */
  77262. _this.weight = 0.58767;
  77263. /**
  77264. * Controls the density of each sample
  77265. */
  77266. _this.density = 0.926;
  77267. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77268. engine = scene.getEngine();
  77269. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77270. // Configure mesh
  77271. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77272. // Configure
  77273. _this._createPass(scene, ratio.passRatio || ratio);
  77274. _this.onActivate = function (camera) {
  77275. if (!_this.isSupported) {
  77276. _this.dispose(camera);
  77277. }
  77278. _this.onActivate = null;
  77279. };
  77280. _this.onApplyObservable.add(function (effect) {
  77281. _this._updateMeshScreenCoordinates(scene);
  77282. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77283. effect.setFloat("exposure", _this.exposure);
  77284. effect.setFloat("decay", _this.decay);
  77285. effect.setFloat("weight", _this.weight);
  77286. effect.setFloat("density", _this.density);
  77287. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77288. });
  77289. return _this;
  77290. }
  77291. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77292. get: function () {
  77293. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77294. return false;
  77295. },
  77296. set: function (useDiffuseColor) {
  77297. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77298. },
  77299. enumerable: true,
  77300. configurable: true
  77301. });
  77302. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77303. return "VolumetricLightScatteringPostProcess";
  77304. };
  77305. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77306. var mesh = subMesh.getMesh();
  77307. // Render this.mesh as default
  77308. if (mesh === this.mesh && mesh.material) {
  77309. return mesh.material.isReady(mesh);
  77310. }
  77311. var defines = [];
  77312. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77313. var material = subMesh.getMaterial();
  77314. // Alpha test
  77315. if (material) {
  77316. if (material.needAlphaTesting()) {
  77317. defines.push("#define ALPHATEST");
  77318. }
  77319. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77320. attribs.push(BABYLON.VertexBuffer.UVKind);
  77321. defines.push("#define UV1");
  77322. }
  77323. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77324. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77325. defines.push("#define UV2");
  77326. }
  77327. }
  77328. // Bones
  77329. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77330. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77331. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77332. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77333. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77334. }
  77335. else {
  77336. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77337. }
  77338. // Instances
  77339. if (useInstances) {
  77340. defines.push("#define INSTANCES");
  77341. attribs.push("world0");
  77342. attribs.push("world1");
  77343. attribs.push("world2");
  77344. attribs.push("world3");
  77345. }
  77346. // Get correct effect
  77347. var join = defines.join("\n");
  77348. if (this._cachedDefines !== join) {
  77349. this._cachedDefines = join;
  77350. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77351. }
  77352. return this._volumetricLightScatteringPass.isReady();
  77353. };
  77354. /**
  77355. * Sets the new light position for light scattering effect
  77356. * @param {BABYLON.Vector3} The new custom light position
  77357. */
  77358. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77359. this.customMeshPosition = position;
  77360. };
  77361. /**
  77362. * Returns the light position for light scattering effect
  77363. * @return {BABYLON.Vector3} The custom light position
  77364. */
  77365. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77366. return this.customMeshPosition;
  77367. };
  77368. /**
  77369. * Disposes the internal assets and detaches the post-process from the camera
  77370. */
  77371. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77372. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77373. if (rttIndex !== -1) {
  77374. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77375. }
  77376. this._volumetricLightScatteringRTT.dispose();
  77377. _super.prototype.dispose.call(this, camera);
  77378. };
  77379. /**
  77380. * Returns the render target texture used by the post-process
  77381. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77382. */
  77383. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77384. return this._volumetricLightScatteringRTT;
  77385. };
  77386. // Private methods
  77387. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77388. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77389. return true;
  77390. }
  77391. return false;
  77392. };
  77393. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77394. var _this = this;
  77395. var engine = scene.getEngine();
  77396. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77397. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77398. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77399. this._volumetricLightScatteringRTT.renderList = null;
  77400. this._volumetricLightScatteringRTT.renderParticles = false;
  77401. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77402. var camera = this.getCamera();
  77403. if (camera) {
  77404. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77405. }
  77406. else {
  77407. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77408. }
  77409. // Custom render function for submeshes
  77410. var renderSubMesh = function (subMesh) {
  77411. var mesh = subMesh.getRenderingMesh();
  77412. if (_this._meshExcluded(mesh)) {
  77413. return;
  77414. }
  77415. var material = subMesh.getMaterial();
  77416. if (!material) {
  77417. return;
  77418. }
  77419. var scene = mesh.getScene();
  77420. var engine = scene.getEngine();
  77421. // Culling
  77422. engine.setState(material.backFaceCulling);
  77423. // Managing instances
  77424. var batch = mesh._getInstancesRenderList(subMesh._id);
  77425. if (batch.mustReturn) {
  77426. return;
  77427. }
  77428. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77429. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77430. var effect = _this._volumetricLightScatteringPass;
  77431. if (mesh === _this.mesh) {
  77432. if (subMesh.effect) {
  77433. effect = subMesh.effect;
  77434. }
  77435. else {
  77436. effect = material.getEffect();
  77437. }
  77438. }
  77439. engine.enableEffect(effect);
  77440. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77441. if (mesh === _this.mesh) {
  77442. material.bind(mesh.getWorldMatrix(), mesh);
  77443. }
  77444. else {
  77445. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77446. // Alpha test
  77447. if (material && material.needAlphaTesting()) {
  77448. var alphaTexture = material.getAlphaTestTexture();
  77449. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77450. if (alphaTexture) {
  77451. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77452. }
  77453. }
  77454. // Bones
  77455. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77456. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77457. }
  77458. }
  77459. // Draw
  77460. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77461. }
  77462. };
  77463. // Render target texture callbacks
  77464. var savedSceneClearColor;
  77465. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77466. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77467. savedSceneClearColor = scene.clearColor;
  77468. scene.clearColor = sceneClearColor;
  77469. });
  77470. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77471. scene.clearColor = savedSceneClearColor;
  77472. });
  77473. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77474. var engine = scene.getEngine();
  77475. var index;
  77476. if (depthOnlySubMeshes.length) {
  77477. engine.setColorWrite(false);
  77478. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77479. renderSubMesh(depthOnlySubMeshes.data[index]);
  77480. }
  77481. engine.setColorWrite(true);
  77482. }
  77483. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77484. renderSubMesh(opaqueSubMeshes.data[index]);
  77485. }
  77486. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77487. renderSubMesh(alphaTestSubMeshes.data[index]);
  77488. }
  77489. if (transparentSubMeshes.length) {
  77490. // Sort sub meshes
  77491. for (index = 0; index < transparentSubMeshes.length; index++) {
  77492. var submesh = transparentSubMeshes.data[index];
  77493. var boundingInfo = submesh.getBoundingInfo();
  77494. if (boundingInfo && scene.activeCamera) {
  77495. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77496. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77497. }
  77498. }
  77499. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77500. sortedArray.sort(function (a, b) {
  77501. // Alpha index first
  77502. if (a._alphaIndex > b._alphaIndex) {
  77503. return 1;
  77504. }
  77505. if (a._alphaIndex < b._alphaIndex) {
  77506. return -1;
  77507. }
  77508. // Then distance to camera
  77509. if (a._distanceToCamera < b._distanceToCamera) {
  77510. return 1;
  77511. }
  77512. if (a._distanceToCamera > b._distanceToCamera) {
  77513. return -1;
  77514. }
  77515. return 0;
  77516. });
  77517. // Render sub meshes
  77518. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77519. for (index = 0; index < sortedArray.length; index++) {
  77520. renderSubMesh(sortedArray[index]);
  77521. }
  77522. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77523. }
  77524. };
  77525. };
  77526. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77527. var transform = scene.getTransformMatrix();
  77528. var meshPosition;
  77529. if (this.useCustomMeshPosition) {
  77530. meshPosition = this.customMeshPosition;
  77531. }
  77532. else if (this.attachedNode) {
  77533. meshPosition = this.attachedNode.position;
  77534. }
  77535. else {
  77536. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77537. }
  77538. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77539. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77540. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77541. if (this.invert)
  77542. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77543. };
  77544. // Static methods
  77545. /**
  77546. * Creates a default mesh for the Volumeric Light Scattering post-process
  77547. * @param {string} The mesh name
  77548. * @param {BABYLON.Scene} The scene where to create the mesh
  77549. * @return {BABYLON.Mesh} the default mesh
  77550. */
  77551. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77552. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77553. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77554. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77555. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77556. mesh.material = material;
  77557. return mesh;
  77558. };
  77559. __decorate([
  77560. BABYLON.serializeAsVector3()
  77561. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77562. __decorate([
  77563. BABYLON.serialize()
  77564. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77565. __decorate([
  77566. BABYLON.serialize()
  77567. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77568. __decorate([
  77569. BABYLON.serializeAsMeshReference()
  77570. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77571. __decorate([
  77572. BABYLON.serialize()
  77573. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77574. __decorate([
  77575. BABYLON.serialize()
  77576. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77577. __decorate([
  77578. BABYLON.serialize()
  77579. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77580. __decorate([
  77581. BABYLON.serialize()
  77582. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77583. __decorate([
  77584. BABYLON.serialize()
  77585. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77586. return VolumetricLightScatteringPostProcess;
  77587. }(BABYLON.PostProcess));
  77588. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77589. })(BABYLON || (BABYLON = {}));
  77590. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77591. //
  77592. // This post-process allows the modification of rendered colors by using
  77593. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77594. //
  77595. // The object needs to be provided an url to a texture containing the color
  77596. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77597. // Use an image editing software to tweak the LUT to match your needs.
  77598. //
  77599. // For an example of a color LUT, see here:
  77600. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77601. // For explanations on color grading, see here:
  77602. // http://udn.epicgames.com/Three/ColorGrading.html
  77603. //
  77604. var BABYLON;
  77605. (function (BABYLON) {
  77606. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77607. __extends(ColorCorrectionPostProcess, _super);
  77608. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77609. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77610. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77611. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77612. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77613. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77614. _this.onApply = function (effect) {
  77615. effect.setTexture("colorTable", _this._colorTableTexture);
  77616. };
  77617. return _this;
  77618. }
  77619. return ColorCorrectionPostProcess;
  77620. }(BABYLON.PostProcess));
  77621. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77622. })(BABYLON || (BABYLON = {}));
  77623. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77624. var BABYLON;
  77625. (function (BABYLON) {
  77626. /** Defines operator used for tonemapping */
  77627. var TonemappingOperator;
  77628. (function (TonemappingOperator) {
  77629. /** Hable */
  77630. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77631. /** Reinhard */
  77632. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77633. /** HejiDawson */
  77634. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77635. /** Photographic */
  77636. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77637. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77638. ;
  77639. /**
  77640. * Defines a post process to apply tone mapping
  77641. */
  77642. var TonemapPostProcess = /** @class */ (function (_super) {
  77643. __extends(TonemapPostProcess, _super);
  77644. /**
  77645. * Creates a new TonemapPostProcess
  77646. * @param name defines the name of the postprocess
  77647. * @param _operator defines the operator to use
  77648. * @param exposureAdjustment defines the required exposure adjustement
  77649. * @param camera defines the camera to use (can be null)
  77650. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77651. * @param engine defines the hosting engine (can be ignore if camera is set)
  77652. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77653. */
  77654. function TonemapPostProcess(name, _operator,
  77655. /** Defines the required exposure adjustement */
  77656. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77658. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77659. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77660. _this._operator = _operator;
  77661. _this.exposureAdjustment = exposureAdjustment;
  77662. var defines = "#define ";
  77663. if (_this._operator === TonemappingOperator.Hable)
  77664. defines += "HABLE_TONEMAPPING";
  77665. else if (_this._operator === TonemappingOperator.Reinhard)
  77666. defines += "REINHARD_TONEMAPPING";
  77667. else if (_this._operator === TonemappingOperator.HejiDawson)
  77668. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77669. else if (_this._operator === TonemappingOperator.Photographic)
  77670. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77671. //sadly a second call to create the effect.
  77672. _this.updateEffect(defines);
  77673. _this.onApply = function (effect) {
  77674. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77675. };
  77676. return _this;
  77677. }
  77678. return TonemapPostProcess;
  77679. }(BABYLON.PostProcess));
  77680. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77681. })(BABYLON || (BABYLON = {}));
  77682. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77683. var BABYLON;
  77684. (function (BABYLON) {
  77685. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77686. __extends(DisplayPassPostProcess, _super);
  77687. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77688. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77689. }
  77690. return DisplayPassPostProcess;
  77691. }(BABYLON.PostProcess));
  77692. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77693. })(BABYLON || (BABYLON = {}));
  77694. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77695. var BABYLON;
  77696. (function (BABYLON) {
  77697. var HighlightsPostProcess = /** @class */ (function (_super) {
  77698. __extends(HighlightsPostProcess, _super);
  77699. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77700. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77701. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77702. }
  77703. return HighlightsPostProcess;
  77704. }(BABYLON.PostProcess));
  77705. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77706. })(BABYLON || (BABYLON = {}));
  77707. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77708. var BABYLON;
  77709. (function (BABYLON) {
  77710. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77711. __extends(ImageProcessingPostProcess, _super);
  77712. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77713. if (camera === void 0) { camera = null; }
  77714. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77715. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77716. _this._fromLinearSpace = true;
  77717. /**
  77718. * Defines cache preventing GC.
  77719. */
  77720. _this._defines = {
  77721. IMAGEPROCESSING: false,
  77722. VIGNETTE: false,
  77723. VIGNETTEBLENDMODEMULTIPLY: false,
  77724. VIGNETTEBLENDMODEOPAQUE: false,
  77725. TONEMAPPING: false,
  77726. CONTRAST: false,
  77727. COLORCURVES: false,
  77728. COLORGRADING: false,
  77729. COLORGRADING3D: false,
  77730. FROMLINEARSPACE: false,
  77731. SAMPLER3DGREENDEPTH: false,
  77732. SAMPLER3DBGRMAP: false,
  77733. IMAGEPROCESSINGPOSTPROCESS: false,
  77734. EXPOSURE: false,
  77735. };
  77736. // Setup the configuration as forced by the constructor. This would then not force the
  77737. // scene materials output in linear space and let untouched the default forward pass.
  77738. if (imageProcessingConfiguration) {
  77739. imageProcessingConfiguration.applyByPostProcess = true;
  77740. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77741. // This will cause the shader to be compiled
  77742. _this.fromLinearSpace = false;
  77743. }
  77744. // Setup the default processing configuration to the scene.
  77745. else {
  77746. _this._attachImageProcessingConfiguration(null, true);
  77747. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77748. }
  77749. _this.onApply = function (effect) {
  77750. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77751. };
  77752. return _this;
  77753. }
  77754. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77755. /**
  77756. * Gets the image processing configuration used either in this material.
  77757. */
  77758. get: function () {
  77759. return this._imageProcessingConfiguration;
  77760. },
  77761. /**
  77762. * Sets the Default image processing configuration used either in the this material.
  77763. *
  77764. * If sets to null, the scene one is in use.
  77765. */
  77766. set: function (value) {
  77767. this._attachImageProcessingConfiguration(value);
  77768. },
  77769. enumerable: true,
  77770. configurable: true
  77771. });
  77772. /**
  77773. * Attaches a new image processing configuration to the PBR Material.
  77774. * @param configuration
  77775. */
  77776. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77777. var _this = this;
  77778. if (doNotBuild === void 0) { doNotBuild = false; }
  77779. if (configuration === this._imageProcessingConfiguration) {
  77780. return;
  77781. }
  77782. // Detaches observer.
  77783. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77784. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77785. }
  77786. // Pick the scene configuration if needed.
  77787. if (!configuration) {
  77788. var scene = null;
  77789. var engine = this.getEngine();
  77790. var camera = this.getCamera();
  77791. if (camera) {
  77792. scene = camera.getScene();
  77793. }
  77794. else if (engine && engine.scenes) {
  77795. var scenes = engine.scenes;
  77796. scene = scenes[scenes.length - 1];
  77797. }
  77798. else {
  77799. scene = BABYLON.Engine.LastCreatedScene;
  77800. }
  77801. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77802. }
  77803. else {
  77804. this._imageProcessingConfiguration = configuration;
  77805. }
  77806. // Attaches observer.
  77807. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77808. _this._updateParameters();
  77809. });
  77810. // Ensure the effect will be rebuilt.
  77811. if (!doNotBuild) {
  77812. this._updateParameters();
  77813. }
  77814. };
  77815. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77816. /**
  77817. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77818. */
  77819. get: function () {
  77820. return this.imageProcessingConfiguration.colorCurves;
  77821. },
  77822. /**
  77823. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77824. */
  77825. set: function (value) {
  77826. this.imageProcessingConfiguration.colorCurves = value;
  77827. },
  77828. enumerable: true,
  77829. configurable: true
  77830. });
  77831. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77832. /**
  77833. * Gets wether the color curves effect is enabled.
  77834. */
  77835. get: function () {
  77836. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77837. },
  77838. /**
  77839. * Sets wether the color curves effect is enabled.
  77840. */
  77841. set: function (value) {
  77842. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77843. },
  77844. enumerable: true,
  77845. configurable: true
  77846. });
  77847. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77848. /**
  77849. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77850. */
  77851. get: function () {
  77852. return this.imageProcessingConfiguration.colorGradingTexture;
  77853. },
  77854. /**
  77855. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77856. */
  77857. set: function (value) {
  77858. this.imageProcessingConfiguration.colorGradingTexture = value;
  77859. },
  77860. enumerable: true,
  77861. configurable: true
  77862. });
  77863. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77864. /**
  77865. * Gets wether the color grading effect is enabled.
  77866. */
  77867. get: function () {
  77868. return this.imageProcessingConfiguration.colorGradingEnabled;
  77869. },
  77870. /**
  77871. * Gets wether the color grading effect is enabled.
  77872. */
  77873. set: function (value) {
  77874. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77875. },
  77876. enumerable: true,
  77877. configurable: true
  77878. });
  77879. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77880. /**
  77881. * Gets exposure used in the effect.
  77882. */
  77883. get: function () {
  77884. return this.imageProcessingConfiguration.exposure;
  77885. },
  77886. /**
  77887. * Sets exposure used in the effect.
  77888. */
  77889. set: function (value) {
  77890. this.imageProcessingConfiguration.exposure = value;
  77891. },
  77892. enumerable: true,
  77893. configurable: true
  77894. });
  77895. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77896. /**
  77897. * Gets wether tonemapping is enabled or not.
  77898. */
  77899. get: function () {
  77900. return this._imageProcessingConfiguration.toneMappingEnabled;
  77901. },
  77902. /**
  77903. * Sets wether tonemapping is enabled or not
  77904. */
  77905. set: function (value) {
  77906. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77907. },
  77908. enumerable: true,
  77909. configurable: true
  77910. });
  77911. ;
  77912. ;
  77913. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77914. /**
  77915. * Gets contrast used in the effect.
  77916. */
  77917. get: function () {
  77918. return this.imageProcessingConfiguration.contrast;
  77919. },
  77920. /**
  77921. * Sets contrast used in the effect.
  77922. */
  77923. set: function (value) {
  77924. this.imageProcessingConfiguration.contrast = value;
  77925. },
  77926. enumerable: true,
  77927. configurable: true
  77928. });
  77929. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77930. /**
  77931. * Gets Vignette stretch size.
  77932. */
  77933. get: function () {
  77934. return this.imageProcessingConfiguration.vignetteStretch;
  77935. },
  77936. /**
  77937. * Sets Vignette stretch size.
  77938. */
  77939. set: function (value) {
  77940. this.imageProcessingConfiguration.vignetteStretch = value;
  77941. },
  77942. enumerable: true,
  77943. configurable: true
  77944. });
  77945. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77946. /**
  77947. * Gets Vignette centre X Offset.
  77948. */
  77949. get: function () {
  77950. return this.imageProcessingConfiguration.vignetteCentreX;
  77951. },
  77952. /**
  77953. * Sets Vignette centre X Offset.
  77954. */
  77955. set: function (value) {
  77956. this.imageProcessingConfiguration.vignetteCentreX = value;
  77957. },
  77958. enumerable: true,
  77959. configurable: true
  77960. });
  77961. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77962. /**
  77963. * Gets Vignette centre Y Offset.
  77964. */
  77965. get: function () {
  77966. return this.imageProcessingConfiguration.vignetteCentreY;
  77967. },
  77968. /**
  77969. * Sets Vignette centre Y Offset.
  77970. */
  77971. set: function (value) {
  77972. this.imageProcessingConfiguration.vignetteCentreY = value;
  77973. },
  77974. enumerable: true,
  77975. configurable: true
  77976. });
  77977. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77978. /**
  77979. * Gets Vignette weight or intensity of the vignette effect.
  77980. */
  77981. get: function () {
  77982. return this.imageProcessingConfiguration.vignetteWeight;
  77983. },
  77984. /**
  77985. * Sets Vignette weight or intensity of the vignette effect.
  77986. */
  77987. set: function (value) {
  77988. this.imageProcessingConfiguration.vignetteWeight = value;
  77989. },
  77990. enumerable: true,
  77991. configurable: true
  77992. });
  77993. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77994. /**
  77995. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77996. * if vignetteEnabled is set to true.
  77997. */
  77998. get: function () {
  77999. return this.imageProcessingConfiguration.vignetteColor;
  78000. },
  78001. /**
  78002. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78003. * if vignetteEnabled is set to true.
  78004. */
  78005. set: function (value) {
  78006. this.imageProcessingConfiguration.vignetteColor = value;
  78007. },
  78008. enumerable: true,
  78009. configurable: true
  78010. });
  78011. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78012. /**
  78013. * Gets Camera field of view used by the Vignette effect.
  78014. */
  78015. get: function () {
  78016. return this.imageProcessingConfiguration.vignetteCameraFov;
  78017. },
  78018. /**
  78019. * Sets Camera field of view used by the Vignette effect.
  78020. */
  78021. set: function (value) {
  78022. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78023. },
  78024. enumerable: true,
  78025. configurable: true
  78026. });
  78027. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78028. /**
  78029. * Gets the vignette blend mode allowing different kind of effect.
  78030. */
  78031. get: function () {
  78032. return this.imageProcessingConfiguration.vignetteBlendMode;
  78033. },
  78034. /**
  78035. * Sets the vignette blend mode allowing different kind of effect.
  78036. */
  78037. set: function (value) {
  78038. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78039. },
  78040. enumerable: true,
  78041. configurable: true
  78042. });
  78043. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78044. /**
  78045. * Gets wether the vignette effect is enabled.
  78046. */
  78047. get: function () {
  78048. return this.imageProcessingConfiguration.vignetteEnabled;
  78049. },
  78050. /**
  78051. * Sets wether the vignette effect is enabled.
  78052. */
  78053. set: function (value) {
  78054. this.imageProcessingConfiguration.vignetteEnabled = value;
  78055. },
  78056. enumerable: true,
  78057. configurable: true
  78058. });
  78059. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78060. /**
  78061. * Gets wether the input of the processing is in Gamma or Linear Space.
  78062. */
  78063. get: function () {
  78064. return this._fromLinearSpace;
  78065. },
  78066. /**
  78067. * Sets wether the input of the processing is in Gamma or Linear Space.
  78068. */
  78069. set: function (value) {
  78070. if (this._fromLinearSpace === value) {
  78071. return;
  78072. }
  78073. this._fromLinearSpace = value;
  78074. this._updateParameters();
  78075. },
  78076. enumerable: true,
  78077. configurable: true
  78078. });
  78079. ImageProcessingPostProcess.prototype.getClassName = function () {
  78080. return "ImageProcessingPostProcess";
  78081. };
  78082. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78083. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78084. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78085. var defines = "";
  78086. for (var define in this._defines) {
  78087. if (this._defines[define]) {
  78088. defines += "#define " + define + ";\r\n";
  78089. }
  78090. }
  78091. var samplers = ["textureSampler"];
  78092. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78093. var uniforms = ["scale"];
  78094. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78095. this.updateEffect(defines, uniforms, samplers);
  78096. };
  78097. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78098. _super.prototype.dispose.call(this, camera);
  78099. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78100. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78101. }
  78102. this.imageProcessingConfiguration.applyByPostProcess = false;
  78103. };
  78104. __decorate([
  78105. BABYLON.serialize()
  78106. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78107. return ImageProcessingPostProcess;
  78108. }(BABYLON.PostProcess));
  78109. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78110. })(BABYLON || (BABYLON = {}));
  78111. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78112. var BABYLON;
  78113. (function (BABYLON) {
  78114. /**
  78115. * Class used to store bone information
  78116. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78117. */
  78118. var Bone = /** @class */ (function (_super) {
  78119. __extends(Bone, _super);
  78120. /**
  78121. * Create a new bone
  78122. * @param name defines the bone name
  78123. * @param skeleton defines the parent skeleton
  78124. * @param parentBone defines the parent (can be null if the bone is the root)
  78125. * @param localMatrix defines the local matrix
  78126. * @param restPose defines the rest pose matrix
  78127. * @param baseMatrix defines the base matrix
  78128. * @param index defines index of the bone in the hiearchy
  78129. */
  78130. function Bone(
  78131. /**
  78132. * defines the bone name
  78133. */
  78134. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78135. if (parentBone === void 0) { parentBone = null; }
  78136. if (localMatrix === void 0) { localMatrix = null; }
  78137. if (restPose === void 0) { restPose = null; }
  78138. if (baseMatrix === void 0) { baseMatrix = null; }
  78139. if (index === void 0) { index = null; }
  78140. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78141. _this.name = name;
  78142. /**
  78143. * Gets the list of child bones
  78144. */
  78145. _this.children = new Array();
  78146. /** Gets the animations associated with this bone */
  78147. _this.animations = new Array();
  78148. /**
  78149. * @hidden Internal only
  78150. * Set this value to map this bone to a different index in the transform matrices
  78151. * Set this value to -1 to exclude the bone from the transform matrices
  78152. */
  78153. _this._index = null;
  78154. _this._absoluteTransform = new BABYLON.Matrix();
  78155. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78156. _this._scalingDeterminant = 1;
  78157. _this._worldTransform = new BABYLON.Matrix();
  78158. _this._needToDecompose = true;
  78159. _this._needToCompose = false;
  78160. _this._skeleton = skeleton;
  78161. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78162. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78163. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78164. _this._index = index;
  78165. skeleton.bones.push(_this);
  78166. _this.setParent(parentBone, false);
  78167. if (baseMatrix || localMatrix) {
  78168. _this._updateDifferenceMatrix();
  78169. }
  78170. return _this;
  78171. }
  78172. Object.defineProperty(Bone.prototype, "_matrix", {
  78173. /** @hidden */
  78174. get: function () {
  78175. this._compose();
  78176. return this._localMatrix;
  78177. },
  78178. /** @hidden */
  78179. set: function (value) {
  78180. this._localMatrix.copyFrom(value);
  78181. this._needToDecompose = true;
  78182. },
  78183. enumerable: true,
  78184. configurable: true
  78185. });
  78186. // Members
  78187. /**
  78188. * Gets the parent skeleton
  78189. * @returns a skeleton
  78190. */
  78191. Bone.prototype.getSkeleton = function () {
  78192. return this._skeleton;
  78193. };
  78194. /**
  78195. * Gets parent bone
  78196. * @returns a bone or null if the bone is the root of the bone hierarchy
  78197. */
  78198. Bone.prototype.getParent = function () {
  78199. return this._parent;
  78200. };
  78201. /**
  78202. * Sets the parent bone
  78203. * @param parent defines the parent (can be null if the bone is the root)
  78204. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78205. */
  78206. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78207. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78208. if (this._parent === parent) {
  78209. return;
  78210. }
  78211. if (this._parent) {
  78212. var index = this._parent.children.indexOf(this);
  78213. if (index !== -1) {
  78214. this._parent.children.splice(index, 1);
  78215. }
  78216. }
  78217. this._parent = parent;
  78218. if (this._parent) {
  78219. this._parent.children.push(this);
  78220. }
  78221. if (updateDifferenceMatrix) {
  78222. this._updateDifferenceMatrix();
  78223. }
  78224. this.markAsDirty();
  78225. };
  78226. /**
  78227. * Gets the local matrix
  78228. * @returns a matrix
  78229. */
  78230. Bone.prototype.getLocalMatrix = function () {
  78231. this._compose();
  78232. return this._localMatrix;
  78233. };
  78234. /**
  78235. * Gets the base matrix (initial matrix which remains unchanged)
  78236. * @returns a matrix
  78237. */
  78238. Bone.prototype.getBaseMatrix = function () {
  78239. return this._baseMatrix;
  78240. };
  78241. /**
  78242. * Gets the rest pose matrix
  78243. * @returns a matrix
  78244. */
  78245. Bone.prototype.getRestPose = function () {
  78246. return this._restPose;
  78247. };
  78248. /**
  78249. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78250. */
  78251. Bone.prototype.getWorldMatrix = function () {
  78252. return this._worldTransform;
  78253. };
  78254. /**
  78255. * Sets the local matrix to rest pose matrix
  78256. */
  78257. Bone.prototype.returnToRest = function () {
  78258. this.updateMatrix(this._restPose.clone());
  78259. };
  78260. /**
  78261. * Gets the inverse of the absolute transform matrix.
  78262. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78263. * @returns a matrix
  78264. */
  78265. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78266. return this._invertedAbsoluteTransform;
  78267. };
  78268. /**
  78269. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78270. * @returns a matrix
  78271. */
  78272. Bone.prototype.getAbsoluteTransform = function () {
  78273. return this._absoluteTransform;
  78274. };
  78275. Object.defineProperty(Bone.prototype, "position", {
  78276. // Properties (matches AbstractMesh properties)
  78277. /** Gets or sets current position (in local space) */
  78278. get: function () {
  78279. this._decompose();
  78280. return this._localPosition;
  78281. },
  78282. set: function (newPosition) {
  78283. this._decompose();
  78284. this._localPosition.copyFrom(newPosition);
  78285. this._markAsDirtyAndCompose();
  78286. },
  78287. enumerable: true,
  78288. configurable: true
  78289. });
  78290. Object.defineProperty(Bone.prototype, "rotation", {
  78291. /** Gets or sets current rotation (in local space) */
  78292. get: function () {
  78293. return this.getRotation();
  78294. },
  78295. set: function (newRotation) {
  78296. this.setRotation(newRotation);
  78297. },
  78298. enumerable: true,
  78299. configurable: true
  78300. });
  78301. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78302. /** Gets or sets current rotation quaternion (in local space) */
  78303. get: function () {
  78304. this._decompose();
  78305. return this._localRotation;
  78306. },
  78307. set: function (newRotation) {
  78308. this.setRotationQuaternion(newRotation);
  78309. },
  78310. enumerable: true,
  78311. configurable: true
  78312. });
  78313. Object.defineProperty(Bone.prototype, "scaling", {
  78314. /** Gets or sets current scaling (in local space) */
  78315. get: function () {
  78316. return this.getScale();
  78317. },
  78318. set: function (newScaling) {
  78319. this.setScale(newScaling);
  78320. },
  78321. enumerable: true,
  78322. configurable: true
  78323. });
  78324. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78325. /**
  78326. * Gets the animation properties override
  78327. */
  78328. get: function () {
  78329. return this._skeleton.animationPropertiesOverride;
  78330. },
  78331. enumerable: true,
  78332. configurable: true
  78333. });
  78334. // Methods
  78335. Bone.prototype._decompose = function () {
  78336. if (!this._needToDecompose) {
  78337. return;
  78338. }
  78339. this._needToDecompose = false;
  78340. if (!this._localScaling) {
  78341. this._localScaling = BABYLON.Vector3.Zero();
  78342. this._localRotation = BABYLON.Quaternion.Zero();
  78343. this._localPosition = BABYLON.Vector3.Zero();
  78344. }
  78345. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78346. };
  78347. Bone.prototype._compose = function () {
  78348. if (!this._needToCompose) {
  78349. return;
  78350. }
  78351. this._needToCompose = false;
  78352. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78353. };
  78354. /**
  78355. * Update the base and local matrices
  78356. * @param matrix defines the new base or local matrix
  78357. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78358. * @param updateLocalMatrix defines if the local matrix should be updated
  78359. */
  78360. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78361. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78362. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78363. this._baseMatrix.copyFrom(matrix);
  78364. if (updateDifferenceMatrix) {
  78365. this._updateDifferenceMatrix();
  78366. }
  78367. if (updateLocalMatrix) {
  78368. this._localMatrix.copyFrom(matrix);
  78369. this._markAsDirtyAndDecompose();
  78370. }
  78371. else {
  78372. this.markAsDirty();
  78373. }
  78374. };
  78375. /** @hidden */
  78376. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78377. if (updateChildren === void 0) { updateChildren = true; }
  78378. if (!rootMatrix) {
  78379. rootMatrix = this._baseMatrix;
  78380. }
  78381. if (this._parent) {
  78382. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78383. }
  78384. else {
  78385. this._absoluteTransform.copyFrom(rootMatrix);
  78386. }
  78387. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78388. if (updateChildren) {
  78389. for (var index = 0; index < this.children.length; index++) {
  78390. this.children[index]._updateDifferenceMatrix();
  78391. }
  78392. }
  78393. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78394. };
  78395. /**
  78396. * Flag the bone as dirty (Forcing it to update everything)
  78397. */
  78398. Bone.prototype.markAsDirty = function () {
  78399. this._currentRenderId++;
  78400. this._childRenderId++;
  78401. this._skeleton._markAsDirty();
  78402. };
  78403. Bone.prototype._markAsDirtyAndCompose = function () {
  78404. this.markAsDirty();
  78405. this._needToCompose = true;
  78406. };
  78407. Bone.prototype._markAsDirtyAndDecompose = function () {
  78408. this.markAsDirty();
  78409. this._needToDecompose = true;
  78410. };
  78411. /**
  78412. * Copy an animation range from another bone
  78413. * @param source defines the source bone
  78414. * @param rangeName defines the range name to copy
  78415. * @param frameOffset defines the frame offset
  78416. * @param rescaleAsRequired defines if rescaling must be applied if required
  78417. * @param skelDimensionsRatio defines the scaling ratio
  78418. * @returns true if operation was successful
  78419. */
  78420. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78421. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78422. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78423. // all animation may be coming from a library skeleton, so may need to create animation
  78424. if (this.animations.length === 0) {
  78425. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78426. this.animations[0].setKeys([]);
  78427. }
  78428. // get animation info / verify there is such a range from the source bone
  78429. var sourceRange = source.animations[0].getRange(rangeName);
  78430. if (!sourceRange) {
  78431. return false;
  78432. }
  78433. var from = sourceRange.from;
  78434. var to = sourceRange.to;
  78435. var sourceKeys = source.animations[0].getKeys();
  78436. // rescaling prep
  78437. var sourceBoneLength = source.length;
  78438. var sourceParent = source.getParent();
  78439. var parent = this.getParent();
  78440. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78441. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78442. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78443. var destKeys = this.animations[0].getKeys();
  78444. // loop vars declaration
  78445. var orig;
  78446. var origTranslation;
  78447. var mat;
  78448. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78449. orig = sourceKeys[key];
  78450. if (orig.frame >= from && orig.frame <= to) {
  78451. if (rescaleAsRequired) {
  78452. mat = orig.value.clone();
  78453. // scale based on parent ratio, when bone has parent
  78454. if (parentScalingReqd) {
  78455. origTranslation = mat.getTranslation();
  78456. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78457. // scale based on skeleton dimension ratio when root bone, and value is passed
  78458. }
  78459. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78460. origTranslation = mat.getTranslation();
  78461. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78462. // use original when root bone, and no data for skelDimensionsRatio
  78463. }
  78464. else {
  78465. mat = orig.value;
  78466. }
  78467. }
  78468. else {
  78469. mat = orig.value;
  78470. }
  78471. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78472. }
  78473. }
  78474. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78475. return true;
  78476. };
  78477. /**
  78478. * Translate the bone in local or world space
  78479. * @param vec The amount to translate the bone
  78480. * @param space The space that the translation is in
  78481. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78482. */
  78483. Bone.prototype.translate = function (vec, space, mesh) {
  78484. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78485. var lm = this.getLocalMatrix();
  78486. if (space == BABYLON.Space.LOCAL) {
  78487. lm.m[12] += vec.x;
  78488. lm.m[13] += vec.y;
  78489. lm.m[14] += vec.z;
  78490. }
  78491. else {
  78492. var wm = null;
  78493. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78494. if (mesh) {
  78495. wm = mesh.getWorldMatrix();
  78496. }
  78497. this._skeleton.computeAbsoluteTransforms();
  78498. var tmat = Bone._tmpMats[0];
  78499. var tvec = Bone._tmpVecs[0];
  78500. if (this._parent) {
  78501. if (mesh && wm) {
  78502. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78503. tmat.multiplyToRef(wm, tmat);
  78504. }
  78505. else {
  78506. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78507. }
  78508. }
  78509. tmat.m[12] = 0;
  78510. tmat.m[13] = 0;
  78511. tmat.m[14] = 0;
  78512. tmat.invert();
  78513. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78514. lm.m[12] += tvec.x;
  78515. lm.m[13] += tvec.y;
  78516. lm.m[14] += tvec.z;
  78517. }
  78518. this._markAsDirtyAndDecompose();
  78519. };
  78520. /**
  78521. * Set the postion of the bone in local or world space
  78522. * @param position The position to set the bone
  78523. * @param space The space that the position is in
  78524. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78525. */
  78526. Bone.prototype.setPosition = function (position, space, mesh) {
  78527. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78528. var lm = this.getLocalMatrix();
  78529. if (space == BABYLON.Space.LOCAL) {
  78530. lm.m[12] = position.x;
  78531. lm.m[13] = position.y;
  78532. lm.m[14] = position.z;
  78533. }
  78534. else {
  78535. var wm = null;
  78536. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78537. if (mesh) {
  78538. wm = mesh.getWorldMatrix();
  78539. }
  78540. this._skeleton.computeAbsoluteTransforms();
  78541. var tmat = Bone._tmpMats[0];
  78542. var vec = Bone._tmpVecs[0];
  78543. if (this._parent) {
  78544. if (mesh && wm) {
  78545. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78546. tmat.multiplyToRef(wm, tmat);
  78547. }
  78548. else {
  78549. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78550. }
  78551. }
  78552. tmat.invert();
  78553. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78554. lm.m[12] = vec.x;
  78555. lm.m[13] = vec.y;
  78556. lm.m[14] = vec.z;
  78557. }
  78558. this._markAsDirtyAndDecompose();
  78559. };
  78560. /**
  78561. * Set the absolute position of the bone (world space)
  78562. * @param position The position to set the bone
  78563. * @param mesh The mesh that this bone is attached to
  78564. */
  78565. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78566. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78567. };
  78568. /**
  78569. * Scale the bone on the x, y and z axes (in local space)
  78570. * @param x The amount to scale the bone on the x axis
  78571. * @param y The amount to scale the bone on the y axis
  78572. * @param z The amount to scale the bone on the z axis
  78573. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78574. */
  78575. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78576. if (scaleChildren === void 0) { scaleChildren = false; }
  78577. var locMat = this.getLocalMatrix();
  78578. // Apply new scaling on top of current local matrix
  78579. var scaleMat = Bone._tmpMats[0];
  78580. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78581. scaleMat.multiplyToRef(locMat, locMat);
  78582. // Invert scaling matrix and apply the inverse to all children
  78583. scaleMat.invert();
  78584. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78585. var child = _a[_i];
  78586. var cm = child.getLocalMatrix();
  78587. cm.multiplyToRef(scaleMat, cm);
  78588. cm.m[12] *= x;
  78589. cm.m[13] *= y;
  78590. cm.m[14] *= z;
  78591. child._markAsDirtyAndDecompose();
  78592. }
  78593. this._markAsDirtyAndDecompose();
  78594. if (scaleChildren) {
  78595. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78596. var child = _c[_b];
  78597. child.scale(x, y, z, scaleChildren);
  78598. }
  78599. }
  78600. };
  78601. /**
  78602. * Set the bone scaling in local space
  78603. * @param scale defines the scaling vector
  78604. */
  78605. Bone.prototype.setScale = function (scale) {
  78606. this._decompose();
  78607. this._localScaling.copyFrom(scale);
  78608. this._markAsDirtyAndCompose();
  78609. };
  78610. /**
  78611. * Gets the current scaling in local space
  78612. * @returns the current scaling vector
  78613. */
  78614. Bone.prototype.getScale = function () {
  78615. this._decompose();
  78616. return this._localScaling;
  78617. };
  78618. /**
  78619. * Gets the current scaling in local space and stores it in a target vector
  78620. * @param result defines the target vector
  78621. */
  78622. Bone.prototype.getScaleToRef = function (result) {
  78623. this._decompose();
  78624. result.copyFrom(this._localScaling);
  78625. };
  78626. /**
  78627. * Set the yaw, pitch, and roll of the bone in local or world space
  78628. * @param yaw The rotation of the bone on the y axis
  78629. * @param pitch The rotation of the bone on the x axis
  78630. * @param roll The rotation of the bone on the z axis
  78631. * @param space The space that the axes of rotation are in
  78632. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78633. */
  78634. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78635. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78636. if (space === BABYLON.Space.LOCAL) {
  78637. var quat = Bone._tmpQuat;
  78638. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78639. this.setRotationQuaternion(quat, space, mesh);
  78640. return;
  78641. }
  78642. var rotMatInv = Bone._tmpMats[0];
  78643. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78644. return;
  78645. }
  78646. var rotMat = Bone._tmpMats[1];
  78647. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78648. rotMatInv.multiplyToRef(rotMat, rotMat);
  78649. this._rotateWithMatrix(rotMat, space, mesh);
  78650. };
  78651. /**
  78652. * Add a rotation to the bone on an axis in local or world space
  78653. * @param axis The axis to rotate the bone on
  78654. * @param amount The amount to rotate the bone
  78655. * @param space The space that the axis is in
  78656. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78657. */
  78658. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78659. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78660. var rmat = Bone._tmpMats[0];
  78661. rmat.m[12] = 0;
  78662. rmat.m[13] = 0;
  78663. rmat.m[14] = 0;
  78664. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78665. this._rotateWithMatrix(rmat, space, mesh);
  78666. };
  78667. /**
  78668. * Set the rotation of the bone to a particular axis angle in local or world space
  78669. * @param axis The axis to rotate the bone on
  78670. * @param angle The angle that the bone should be rotated to
  78671. * @param space The space that the axis is in
  78672. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78673. */
  78674. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78675. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78676. if (space === BABYLON.Space.LOCAL) {
  78677. var quat = Bone._tmpQuat;
  78678. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78679. this.setRotationQuaternion(quat, space, mesh);
  78680. return;
  78681. }
  78682. var rotMatInv = Bone._tmpMats[0];
  78683. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78684. return;
  78685. }
  78686. var rotMat = Bone._tmpMats[1];
  78687. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78688. rotMatInv.multiplyToRef(rotMat, rotMat);
  78689. this._rotateWithMatrix(rotMat, space, mesh);
  78690. };
  78691. /**
  78692. * Set the euler rotation of the bone in local of world space
  78693. * @param rotation The euler rotation that the bone should be set to
  78694. * @param space The space that the rotation is in
  78695. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78696. */
  78697. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78699. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78700. };
  78701. /**
  78702. * Set the quaternion rotation of the bone in local of world space
  78703. * @param quat The quaternion rotation that the bone should be set to
  78704. * @param space The space that the rotation is in
  78705. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78706. */
  78707. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78709. if (space === BABYLON.Space.LOCAL) {
  78710. this._decompose();
  78711. this._localRotation.copyFrom(quat);
  78712. this._markAsDirtyAndCompose();
  78713. return;
  78714. }
  78715. var rotMatInv = Bone._tmpMats[0];
  78716. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78717. return;
  78718. }
  78719. var rotMat = Bone._tmpMats[1];
  78720. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78721. rotMatInv.multiplyToRef(rotMat, rotMat);
  78722. this._rotateWithMatrix(rotMat, space, mesh);
  78723. };
  78724. /**
  78725. * Set the rotation matrix of the bone in local of world space
  78726. * @param rotMat The rotation matrix that the bone should be set to
  78727. * @param space The space that the rotation is in
  78728. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78729. */
  78730. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78732. if (space === BABYLON.Space.LOCAL) {
  78733. var quat = Bone._tmpQuat;
  78734. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78735. this.setRotationQuaternion(quat, space, mesh);
  78736. return;
  78737. }
  78738. var rotMatInv = Bone._tmpMats[0];
  78739. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78740. return;
  78741. }
  78742. var rotMat2 = Bone._tmpMats[1];
  78743. rotMat2.copyFrom(rotMat);
  78744. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78745. this._rotateWithMatrix(rotMat2, space, mesh);
  78746. };
  78747. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78748. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78749. var lmat = this.getLocalMatrix();
  78750. var lx = lmat.m[12];
  78751. var ly = lmat.m[13];
  78752. var lz = lmat.m[14];
  78753. var parent = this.getParent();
  78754. var parentScale = Bone._tmpMats[3];
  78755. var parentScaleInv = Bone._tmpMats[4];
  78756. if (parent && space == BABYLON.Space.WORLD) {
  78757. if (mesh) {
  78758. parentScale.copyFrom(mesh.getWorldMatrix());
  78759. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78760. }
  78761. else {
  78762. parentScale.copyFrom(parent.getAbsoluteTransform());
  78763. }
  78764. parentScaleInv.copyFrom(parentScale);
  78765. parentScaleInv.invert();
  78766. lmat.multiplyToRef(parentScale, lmat);
  78767. lmat.multiplyToRef(rmat, lmat);
  78768. lmat.multiplyToRef(parentScaleInv, lmat);
  78769. }
  78770. else {
  78771. if (space == BABYLON.Space.WORLD && mesh) {
  78772. parentScale.copyFrom(mesh.getWorldMatrix());
  78773. parentScaleInv.copyFrom(parentScale);
  78774. parentScaleInv.invert();
  78775. lmat.multiplyToRef(parentScale, lmat);
  78776. lmat.multiplyToRef(rmat, lmat);
  78777. lmat.multiplyToRef(parentScaleInv, lmat);
  78778. }
  78779. else {
  78780. lmat.multiplyToRef(rmat, lmat);
  78781. }
  78782. }
  78783. lmat.m[12] = lx;
  78784. lmat.m[13] = ly;
  78785. lmat.m[14] = lz;
  78786. this.computeAbsoluteTransforms();
  78787. this._markAsDirtyAndDecompose();
  78788. };
  78789. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78790. var scaleMatrix = Bone._tmpMats[2];
  78791. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78792. if (mesh) {
  78793. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78794. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78795. }
  78796. rotMatInv.invert();
  78797. if (isNaN(rotMatInv.m[0])) {
  78798. // Matrix failed to invert.
  78799. // This can happen if scale is zero for example.
  78800. return false;
  78801. }
  78802. scaleMatrix.m[0] *= this._scalingDeterminant;
  78803. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78804. return true;
  78805. };
  78806. /**
  78807. * Get the position of the bone in local or world space
  78808. * @param space The space that the returned position is in
  78809. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78810. * @returns The position of the bone
  78811. */
  78812. Bone.prototype.getPosition = function (space, mesh) {
  78813. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78814. if (mesh === void 0) { mesh = null; }
  78815. var pos = BABYLON.Vector3.Zero();
  78816. this.getPositionToRef(space, mesh, pos);
  78817. return pos;
  78818. };
  78819. /**
  78820. * Copy the position of the bone to a vector3 in local or world space
  78821. * @param space The space that the returned position is in
  78822. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78823. * @param result The vector3 to copy the position to
  78824. */
  78825. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78827. if (space == BABYLON.Space.LOCAL) {
  78828. var lm = this.getLocalMatrix();
  78829. result.x = lm.m[12];
  78830. result.y = lm.m[13];
  78831. result.z = lm.m[14];
  78832. }
  78833. else {
  78834. var wm = null;
  78835. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78836. if (mesh) {
  78837. wm = mesh.getWorldMatrix();
  78838. }
  78839. this._skeleton.computeAbsoluteTransforms();
  78840. var tmat = Bone._tmpMats[0];
  78841. if (mesh && wm) {
  78842. tmat.copyFrom(this.getAbsoluteTransform());
  78843. tmat.multiplyToRef(wm, tmat);
  78844. }
  78845. else {
  78846. tmat = this.getAbsoluteTransform();
  78847. }
  78848. result.x = tmat.m[12];
  78849. result.y = tmat.m[13];
  78850. result.z = tmat.m[14];
  78851. }
  78852. };
  78853. /**
  78854. * Get the absolute position of the bone (world space)
  78855. * @param mesh The mesh that this bone is attached to
  78856. * @returns The absolute position of the bone
  78857. */
  78858. Bone.prototype.getAbsolutePosition = function (mesh) {
  78859. if (mesh === void 0) { mesh = null; }
  78860. var pos = BABYLON.Vector3.Zero();
  78861. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78862. return pos;
  78863. };
  78864. /**
  78865. * Copy the absolute position of the bone (world space) to the result param
  78866. * @param mesh The mesh that this bone is attached to
  78867. * @param result The vector3 to copy the absolute position to
  78868. */
  78869. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78870. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78871. };
  78872. /**
  78873. * Compute the absolute transforms of this bone and its children
  78874. */
  78875. Bone.prototype.computeAbsoluteTransforms = function () {
  78876. this._compose();
  78877. if (this._parent) {
  78878. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78879. }
  78880. else {
  78881. this._absoluteTransform.copyFrom(this._localMatrix);
  78882. var poseMatrix = this._skeleton.getPoseMatrix();
  78883. if (poseMatrix) {
  78884. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78885. }
  78886. }
  78887. var children = this.children;
  78888. var len = children.length;
  78889. for (var i = 0; i < len; i++) {
  78890. children[i].computeAbsoluteTransforms();
  78891. }
  78892. };
  78893. /**
  78894. * Get the world direction from an axis that is in the local space of the bone
  78895. * @param localAxis The local direction that is used to compute the world direction
  78896. * @param mesh The mesh that this bone is attached to
  78897. * @returns The world direction
  78898. */
  78899. Bone.prototype.getDirection = function (localAxis, mesh) {
  78900. if (mesh === void 0) { mesh = null; }
  78901. var result = BABYLON.Vector3.Zero();
  78902. this.getDirectionToRef(localAxis, mesh, result);
  78903. return result;
  78904. };
  78905. /**
  78906. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78907. * @param localAxis The local direction that is used to compute the world direction
  78908. * @param mesh The mesh that this bone is attached to
  78909. * @param result The vector3 that the world direction will be copied to
  78910. */
  78911. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78912. if (mesh === void 0) { mesh = null; }
  78913. var wm = null;
  78914. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78915. if (mesh) {
  78916. wm = mesh.getWorldMatrix();
  78917. }
  78918. this._skeleton.computeAbsoluteTransforms();
  78919. var mat = Bone._tmpMats[0];
  78920. mat.copyFrom(this.getAbsoluteTransform());
  78921. if (mesh && wm) {
  78922. mat.multiplyToRef(wm, mat);
  78923. }
  78924. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78925. result.normalize();
  78926. };
  78927. /**
  78928. * Get the euler rotation of the bone in local or world space
  78929. * @param space The space that the rotation should be in
  78930. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78931. * @returns The euler rotation
  78932. */
  78933. Bone.prototype.getRotation = function (space, mesh) {
  78934. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78935. if (mesh === void 0) { mesh = null; }
  78936. var result = BABYLON.Vector3.Zero();
  78937. this.getRotationToRef(space, mesh, result);
  78938. return result;
  78939. };
  78940. /**
  78941. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78942. * @param space The space that the rotation should be in
  78943. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78944. * @param result The vector3 that the rotation should be copied to
  78945. */
  78946. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78947. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78948. if (mesh === void 0) { mesh = null; }
  78949. var quat = Bone._tmpQuat;
  78950. this.getRotationQuaternionToRef(space, mesh, quat);
  78951. quat.toEulerAnglesToRef(result);
  78952. };
  78953. /**
  78954. * Get the quaternion rotation of the bone in either local or world space
  78955. * @param space The space that the rotation should be in
  78956. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78957. * @returns The quaternion rotation
  78958. */
  78959. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78961. if (mesh === void 0) { mesh = null; }
  78962. var result = BABYLON.Quaternion.Identity();
  78963. this.getRotationQuaternionToRef(space, mesh, result);
  78964. return result;
  78965. };
  78966. /**
  78967. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78968. * @param space The space that the rotation should be in
  78969. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78970. * @param result The quaternion that the rotation should be copied to
  78971. */
  78972. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78973. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78974. if (mesh === void 0) { mesh = null; }
  78975. if (space == BABYLON.Space.LOCAL) {
  78976. this._decompose();
  78977. result.copyFrom(this._localRotation);
  78978. }
  78979. else {
  78980. var mat = Bone._tmpMats[0];
  78981. var amat = this.getAbsoluteTransform();
  78982. if (mesh) {
  78983. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78984. }
  78985. else {
  78986. mat.copyFrom(amat);
  78987. }
  78988. mat.m[0] *= this._scalingDeterminant;
  78989. mat.m[1] *= this._scalingDeterminant;
  78990. mat.m[2] *= this._scalingDeterminant;
  78991. mat.decompose(undefined, result, undefined);
  78992. }
  78993. };
  78994. /**
  78995. * Get the rotation matrix of the bone in local or world space
  78996. * @param space The space that the rotation should be in
  78997. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78998. * @returns The rotation matrix
  78999. */
  79000. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79001. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79002. var result = BABYLON.Matrix.Identity();
  79003. this.getRotationMatrixToRef(space, mesh, result);
  79004. return result;
  79005. };
  79006. /**
  79007. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79008. * @param space The space that the rotation should be in
  79009. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79010. * @param result The quaternion that the rotation should be copied to
  79011. */
  79012. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79013. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79014. if (space == BABYLON.Space.LOCAL) {
  79015. this.getLocalMatrix().getRotationMatrixToRef(result);
  79016. }
  79017. else {
  79018. var mat = Bone._tmpMats[0];
  79019. var amat = this.getAbsoluteTransform();
  79020. if (mesh) {
  79021. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79022. }
  79023. else {
  79024. mat.copyFrom(amat);
  79025. }
  79026. mat.m[0] *= this._scalingDeterminant;
  79027. mat.m[1] *= this._scalingDeterminant;
  79028. mat.m[2] *= this._scalingDeterminant;
  79029. mat.getRotationMatrixToRef(result);
  79030. }
  79031. };
  79032. /**
  79033. * Get the world position of a point that is in the local space of the bone
  79034. * @param position The local position
  79035. * @param mesh The mesh that this bone is attached to
  79036. * @returns The world position
  79037. */
  79038. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79039. if (mesh === void 0) { mesh = null; }
  79040. var result = BABYLON.Vector3.Zero();
  79041. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79042. return result;
  79043. };
  79044. /**
  79045. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79046. * @param position The local position
  79047. * @param mesh The mesh that this bone is attached to
  79048. * @param result The vector3 that the world position should be copied to
  79049. */
  79050. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79051. if (mesh === void 0) { mesh = null; }
  79052. var wm = null;
  79053. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79054. if (mesh) {
  79055. wm = mesh.getWorldMatrix();
  79056. }
  79057. this._skeleton.computeAbsoluteTransforms();
  79058. var tmat = Bone._tmpMats[0];
  79059. if (mesh && wm) {
  79060. tmat.copyFrom(this.getAbsoluteTransform());
  79061. tmat.multiplyToRef(wm, tmat);
  79062. }
  79063. else {
  79064. tmat = this.getAbsoluteTransform();
  79065. }
  79066. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79067. };
  79068. /**
  79069. * Get the local position of a point that is in world space
  79070. * @param position The world position
  79071. * @param mesh The mesh that this bone is attached to
  79072. * @returns The local position
  79073. */
  79074. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79075. if (mesh === void 0) { mesh = null; }
  79076. var result = BABYLON.Vector3.Zero();
  79077. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79078. return result;
  79079. };
  79080. /**
  79081. * Get the local position of a point that is in world space and copy it to the result param
  79082. * @param position The world position
  79083. * @param mesh The mesh that this bone is attached to
  79084. * @param result The vector3 that the local position should be copied to
  79085. */
  79086. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79087. if (mesh === void 0) { mesh = null; }
  79088. var wm = null;
  79089. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79090. if (mesh) {
  79091. wm = mesh.getWorldMatrix();
  79092. }
  79093. this._skeleton.computeAbsoluteTransforms();
  79094. var tmat = Bone._tmpMats[0];
  79095. tmat.copyFrom(this.getAbsoluteTransform());
  79096. if (mesh && wm) {
  79097. tmat.multiplyToRef(wm, tmat);
  79098. }
  79099. tmat.invert();
  79100. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79101. };
  79102. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79103. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79104. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79105. return Bone;
  79106. }(BABYLON.Node));
  79107. BABYLON.Bone = Bone;
  79108. })(BABYLON || (BABYLON = {}));
  79109. //# sourceMappingURL=babylon.bone.js.map
  79110. var BABYLON;
  79111. (function (BABYLON) {
  79112. /**
  79113. * Class used to apply inverse kinematics to bones
  79114. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79115. */
  79116. var BoneIKController = /** @class */ (function () {
  79117. /**
  79118. * Creates a new BoneIKController
  79119. * @param mesh defines the mesh to control
  79120. * @param bone defines the bone to control
  79121. * @param options defines options to set up the controller
  79122. */
  79123. function BoneIKController(mesh, bone, options) {
  79124. /**
  79125. * Gets or sets the target position
  79126. */
  79127. this.targetPosition = BABYLON.Vector3.Zero();
  79128. /**
  79129. * Gets or sets the pole target position
  79130. */
  79131. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79132. /**
  79133. * Gets or sets the pole target local offset
  79134. */
  79135. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79136. /**
  79137. * Gets or sets the pole angle
  79138. */
  79139. this.poleAngle = 0;
  79140. /**
  79141. * 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)
  79142. */
  79143. this.slerpAmount = 1;
  79144. this._bone1Quat = BABYLON.Quaternion.Identity();
  79145. this._bone1Mat = BABYLON.Matrix.Identity();
  79146. this._bone2Ang = Math.PI;
  79147. this._maxAngle = Math.PI;
  79148. this._rightHandedSystem = false;
  79149. this._bendAxis = BABYLON.Vector3.Right();
  79150. this._slerping = false;
  79151. this._adjustRoll = 0;
  79152. this._bone2 = bone;
  79153. this._bone1 = bone.getParent();
  79154. if (!this._bone1) {
  79155. return;
  79156. }
  79157. this.mesh = mesh;
  79158. var bonePos = bone.getPosition();
  79159. if (bone.getAbsoluteTransform().determinant() > 0) {
  79160. this._rightHandedSystem = true;
  79161. this._bendAxis.x = 0;
  79162. this._bendAxis.y = 0;
  79163. this._bendAxis.z = -1;
  79164. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79165. this._adjustRoll = Math.PI * .5;
  79166. this._bendAxis.z = 1;
  79167. }
  79168. }
  79169. if (this._bone1.length) {
  79170. var boneScale1 = this._bone1.getScale();
  79171. var boneScale2 = this._bone2.getScale();
  79172. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79173. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79174. }
  79175. else if (this._bone1.children[0]) {
  79176. mesh.computeWorldMatrix(true);
  79177. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79178. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79179. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79180. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79181. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79182. }
  79183. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79184. this.maxAngle = Math.PI;
  79185. if (options) {
  79186. if (options.targetMesh) {
  79187. this.targetMesh = options.targetMesh;
  79188. this.targetMesh.computeWorldMatrix(true);
  79189. }
  79190. if (options.poleTargetMesh) {
  79191. this.poleTargetMesh = options.poleTargetMesh;
  79192. this.poleTargetMesh.computeWorldMatrix(true);
  79193. }
  79194. else if (options.poleTargetBone) {
  79195. this.poleTargetBone = options.poleTargetBone;
  79196. }
  79197. else if (this._bone1.getParent()) {
  79198. this.poleTargetBone = this._bone1.getParent();
  79199. }
  79200. if (options.poleTargetLocalOffset) {
  79201. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79202. }
  79203. if (options.poleAngle) {
  79204. this.poleAngle = options.poleAngle;
  79205. }
  79206. if (options.bendAxis) {
  79207. this._bendAxis.copyFrom(options.bendAxis);
  79208. }
  79209. if (options.maxAngle) {
  79210. this.maxAngle = options.maxAngle;
  79211. }
  79212. if (options.slerpAmount) {
  79213. this.slerpAmount = options.slerpAmount;
  79214. }
  79215. }
  79216. }
  79217. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79218. /**
  79219. * Gets or sets maximum allowed angle
  79220. */
  79221. get: function () {
  79222. return this._maxAngle;
  79223. },
  79224. set: function (value) {
  79225. this._setMaxAngle(value);
  79226. },
  79227. enumerable: true,
  79228. configurable: true
  79229. });
  79230. BoneIKController.prototype._setMaxAngle = function (ang) {
  79231. if (ang < 0) {
  79232. ang = 0;
  79233. }
  79234. if (ang > Math.PI || ang == undefined) {
  79235. ang = Math.PI;
  79236. }
  79237. this._maxAngle = ang;
  79238. var a = this._bone1Length;
  79239. var b = this._bone2Length;
  79240. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79241. };
  79242. /**
  79243. * Force the controller to update the bones
  79244. */
  79245. BoneIKController.prototype.update = function () {
  79246. var bone1 = this._bone1;
  79247. if (!bone1) {
  79248. return;
  79249. }
  79250. var target = this.targetPosition;
  79251. var poleTarget = this.poleTargetPosition;
  79252. var mat1 = BoneIKController._tmpMats[0];
  79253. var mat2 = BoneIKController._tmpMats[1];
  79254. if (this.targetMesh) {
  79255. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79256. }
  79257. if (this.poleTargetBone) {
  79258. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79259. }
  79260. else if (this.poleTargetMesh) {
  79261. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79262. }
  79263. var bonePos = BoneIKController._tmpVecs[0];
  79264. var zaxis = BoneIKController._tmpVecs[1];
  79265. var xaxis = BoneIKController._tmpVecs[2];
  79266. var yaxis = BoneIKController._tmpVecs[3];
  79267. var upAxis = BoneIKController._tmpVecs[4];
  79268. var _tmpQuat = BoneIKController._tmpQuat;
  79269. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79270. poleTarget.subtractToRef(bonePos, upAxis);
  79271. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79272. upAxis.y = 1;
  79273. }
  79274. else {
  79275. upAxis.normalize();
  79276. }
  79277. target.subtractToRef(bonePos, yaxis);
  79278. yaxis.normalize();
  79279. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79280. zaxis.normalize();
  79281. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79282. xaxis.normalize();
  79283. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79284. var a = this._bone1Length;
  79285. var b = this._bone2Length;
  79286. var c = BABYLON.Vector3.Distance(bonePos, target);
  79287. if (this._maxReach > 0) {
  79288. c = Math.min(this._maxReach, c);
  79289. }
  79290. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79291. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79292. if (acosa > 1) {
  79293. acosa = 1;
  79294. }
  79295. if (acosb > 1) {
  79296. acosb = 1;
  79297. }
  79298. if (acosa < -1) {
  79299. acosa = -1;
  79300. }
  79301. if (acosb < -1) {
  79302. acosb = -1;
  79303. }
  79304. var angA = Math.acos(acosa);
  79305. var angB = Math.acos(acosb);
  79306. var angC = -angA - angB;
  79307. if (this._rightHandedSystem) {
  79308. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79309. mat2.multiplyToRef(mat1, mat1);
  79310. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79311. mat2.multiplyToRef(mat1, mat1);
  79312. }
  79313. else {
  79314. var _tmpVec = BoneIKController._tmpVecs[5];
  79315. _tmpVec.copyFrom(this._bendAxis);
  79316. _tmpVec.x *= -1;
  79317. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79318. mat2.multiplyToRef(mat1, mat1);
  79319. }
  79320. if (this.poleAngle) {
  79321. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79322. mat1.multiplyToRef(mat2, mat1);
  79323. }
  79324. if (this._bone1) {
  79325. if (this.slerpAmount < 1) {
  79326. if (!this._slerping) {
  79327. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79328. }
  79329. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79330. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79331. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79332. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79333. this._slerping = true;
  79334. }
  79335. else {
  79336. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79337. this._bone1Mat.copyFrom(mat1);
  79338. this._slerping = false;
  79339. }
  79340. }
  79341. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79342. this._bone2Ang = angC;
  79343. };
  79344. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79345. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79346. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79347. return BoneIKController;
  79348. }());
  79349. BABYLON.BoneIKController = BoneIKController;
  79350. })(BABYLON || (BABYLON = {}));
  79351. //# sourceMappingURL=babylon.boneIKController.js.map
  79352. var BABYLON;
  79353. (function (BABYLON) {
  79354. /**
  79355. * Class used to make a bone look toward a point in space
  79356. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79357. */
  79358. var BoneLookController = /** @class */ (function () {
  79359. /**
  79360. * Create a BoneLookController
  79361. * @param mesh the mesh that the bone belongs to
  79362. * @param bone the bone that will be looking to the target
  79363. * @param target the target Vector3 to look at
  79364. * @param settings optional settings:
  79365. * * maxYaw: the maximum angle the bone will yaw to
  79366. * * minYaw: the minimum angle the bone will yaw to
  79367. * * maxPitch: the maximum angle the bone will pitch to
  79368. * * minPitch: the minimum angle the bone will yaw to
  79369. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79370. * * upAxis: the up axis of the coordinate system
  79371. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79372. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79373. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79374. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79375. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79376. * * adjustRoll: used to make an adjustment to the roll of the bone
  79377. **/
  79378. function BoneLookController(mesh, bone, target, options) {
  79379. /**
  79380. * The up axis of the coordinate system that is used when the bone is rotated
  79381. */
  79382. this.upAxis = BABYLON.Vector3.Up();
  79383. /**
  79384. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79385. */
  79386. this.upAxisSpace = BABYLON.Space.LOCAL;
  79387. /**
  79388. * Used to make an adjustment to the yaw of the bone
  79389. */
  79390. this.adjustYaw = 0;
  79391. /**
  79392. * Used to make an adjustment to the pitch of the bone
  79393. */
  79394. this.adjustPitch = 0;
  79395. /**
  79396. * Used to make an adjustment to the roll of the bone
  79397. */
  79398. this.adjustRoll = 0;
  79399. /**
  79400. * 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)
  79401. */
  79402. this.slerpAmount = 1;
  79403. this._boneQuat = BABYLON.Quaternion.Identity();
  79404. this._slerping = false;
  79405. this._firstFrameSkipped = false;
  79406. this._fowardAxis = BABYLON.Vector3.Forward();
  79407. this.mesh = mesh;
  79408. this.bone = bone;
  79409. this.target = target;
  79410. if (options) {
  79411. if (options.adjustYaw) {
  79412. this.adjustYaw = options.adjustYaw;
  79413. }
  79414. if (options.adjustPitch) {
  79415. this.adjustPitch = options.adjustPitch;
  79416. }
  79417. if (options.adjustRoll) {
  79418. this.adjustRoll = options.adjustRoll;
  79419. }
  79420. if (options.maxYaw != null) {
  79421. this.maxYaw = options.maxYaw;
  79422. }
  79423. else {
  79424. this.maxYaw = Math.PI;
  79425. }
  79426. if (options.minYaw != null) {
  79427. this.minYaw = options.minYaw;
  79428. }
  79429. else {
  79430. this.minYaw = -Math.PI;
  79431. }
  79432. if (options.maxPitch != null) {
  79433. this.maxPitch = options.maxPitch;
  79434. }
  79435. else {
  79436. this.maxPitch = Math.PI;
  79437. }
  79438. if (options.minPitch != null) {
  79439. this.minPitch = options.minPitch;
  79440. }
  79441. else {
  79442. this.minPitch = -Math.PI;
  79443. }
  79444. if (options.slerpAmount != null) {
  79445. this.slerpAmount = options.slerpAmount;
  79446. }
  79447. if (options.upAxis != null) {
  79448. this.upAxis = options.upAxis;
  79449. }
  79450. if (options.upAxisSpace != null) {
  79451. this.upAxisSpace = options.upAxisSpace;
  79452. }
  79453. if (options.yawAxis != null || options.pitchAxis != null) {
  79454. var newYawAxis = BABYLON.Axis.Y;
  79455. var newPitchAxis = BABYLON.Axis.X;
  79456. if (options.yawAxis != null) {
  79457. newYawAxis = options.yawAxis.clone();
  79458. newYawAxis.normalize();
  79459. }
  79460. if (options.pitchAxis != null) {
  79461. newPitchAxis = options.pitchAxis.clone();
  79462. newPitchAxis.normalize();
  79463. }
  79464. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79465. this._transformYawPitch = BABYLON.Matrix.Identity();
  79466. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79467. this._transformYawPitchInv = this._transformYawPitch.clone();
  79468. this._transformYawPitch.invert();
  79469. }
  79470. }
  79471. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79472. this.upAxisSpace = BABYLON.Space.LOCAL;
  79473. }
  79474. }
  79475. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79476. /**
  79477. * Gets or sets the minimum yaw angle that the bone can look to
  79478. */
  79479. get: function () {
  79480. return this._minYaw;
  79481. },
  79482. set: function (value) {
  79483. this._minYaw = value;
  79484. this._minYawSin = Math.sin(value);
  79485. this._minYawCos = Math.cos(value);
  79486. if (this._maxYaw != null) {
  79487. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79488. this._yawRange = this._maxYaw - this._minYaw;
  79489. }
  79490. },
  79491. enumerable: true,
  79492. configurable: true
  79493. });
  79494. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79495. /**
  79496. * Gets or sets the maximum yaw angle that the bone can look to
  79497. */
  79498. get: function () {
  79499. return this._maxYaw;
  79500. },
  79501. set: function (value) {
  79502. this._maxYaw = value;
  79503. this._maxYawSin = Math.sin(value);
  79504. this._maxYawCos = Math.cos(value);
  79505. if (this._minYaw != null) {
  79506. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79507. this._yawRange = this._maxYaw - this._minYaw;
  79508. }
  79509. },
  79510. enumerable: true,
  79511. configurable: true
  79512. });
  79513. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79514. /**
  79515. * Gets or sets the minimum pitch angle that the bone can look to
  79516. */
  79517. get: function () {
  79518. return this._minPitch;
  79519. },
  79520. set: function (value) {
  79521. this._minPitch = value;
  79522. this._minPitchTan = Math.tan(value);
  79523. },
  79524. enumerable: true,
  79525. configurable: true
  79526. });
  79527. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79528. /**
  79529. * Gets or sets the maximum pitch angle that the bone can look to
  79530. */
  79531. get: function () {
  79532. return this._maxPitch;
  79533. },
  79534. set: function (value) {
  79535. this._maxPitch = value;
  79536. this._maxPitchTan = Math.tan(value);
  79537. },
  79538. enumerable: true,
  79539. configurable: true
  79540. });
  79541. /**
  79542. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79543. */
  79544. BoneLookController.prototype.update = function () {
  79545. //skip the first frame when slerping so that the mesh rotation is correct
  79546. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79547. this._firstFrameSkipped = true;
  79548. return;
  79549. }
  79550. var bone = this.bone;
  79551. var bonePos = BoneLookController._tmpVecs[0];
  79552. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79553. var target = this.target;
  79554. var _tmpMat1 = BoneLookController._tmpMats[0];
  79555. var _tmpMat2 = BoneLookController._tmpMats[1];
  79556. var mesh = this.mesh;
  79557. var parentBone = bone.getParent();
  79558. var upAxis = BoneLookController._tmpVecs[1];
  79559. upAxis.copyFrom(this.upAxis);
  79560. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79561. if (this._transformYawPitch) {
  79562. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79563. }
  79564. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79565. }
  79566. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79567. mesh.getDirectionToRef(upAxis, upAxis);
  79568. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79569. upAxis.normalize();
  79570. }
  79571. }
  79572. var checkYaw = false;
  79573. var checkPitch = false;
  79574. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79575. checkYaw = true;
  79576. }
  79577. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79578. checkPitch = true;
  79579. }
  79580. if (checkYaw || checkPitch) {
  79581. var spaceMat = BoneLookController._tmpMats[2];
  79582. var spaceMatInv = BoneLookController._tmpMats[3];
  79583. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79584. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79585. }
  79586. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79587. spaceMat.copyFrom(mesh.getWorldMatrix());
  79588. }
  79589. else {
  79590. var forwardAxis = BoneLookController._tmpVecs[2];
  79591. forwardAxis.copyFrom(this._fowardAxis);
  79592. if (this._transformYawPitch) {
  79593. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79594. }
  79595. if (parentBone) {
  79596. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79597. }
  79598. else {
  79599. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79600. }
  79601. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79602. rightAxis.normalize();
  79603. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79604. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79605. }
  79606. spaceMat.invertToRef(spaceMatInv);
  79607. var xzlen = null;
  79608. if (checkPitch) {
  79609. var localTarget = BoneLookController._tmpVecs[3];
  79610. target.subtractToRef(bonePos, localTarget);
  79611. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79612. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79613. var pitch = Math.atan2(localTarget.y, xzlen);
  79614. var newPitch = pitch;
  79615. if (pitch > this._maxPitch) {
  79616. localTarget.y = this._maxPitchTan * xzlen;
  79617. newPitch = this._maxPitch;
  79618. }
  79619. else if (pitch < this._minPitch) {
  79620. localTarget.y = this._minPitchTan * xzlen;
  79621. newPitch = this._minPitch;
  79622. }
  79623. if (pitch != newPitch) {
  79624. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79625. localTarget.addInPlace(bonePos);
  79626. target = localTarget;
  79627. }
  79628. }
  79629. if (checkYaw) {
  79630. var localTarget = BoneLookController._tmpVecs[4];
  79631. target.subtractToRef(bonePos, localTarget);
  79632. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79633. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79634. var newYaw = yaw;
  79635. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79636. if (xzlen == null) {
  79637. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79638. }
  79639. if (this._yawRange > Math.PI) {
  79640. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79641. localTarget.z = this._maxYawCos * xzlen;
  79642. localTarget.x = this._maxYawSin * xzlen;
  79643. newYaw = this._maxYaw;
  79644. }
  79645. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79646. localTarget.z = this._minYawCos * xzlen;
  79647. localTarget.x = this._minYawSin * xzlen;
  79648. newYaw = this._minYaw;
  79649. }
  79650. }
  79651. else {
  79652. if (yaw > this._maxYaw) {
  79653. localTarget.z = this._maxYawCos * xzlen;
  79654. localTarget.x = this._maxYawSin * xzlen;
  79655. newYaw = this._maxYaw;
  79656. }
  79657. else if (yaw < this._minYaw) {
  79658. localTarget.z = this._minYawCos * xzlen;
  79659. localTarget.x = this._minYawSin * xzlen;
  79660. newYaw = this._minYaw;
  79661. }
  79662. }
  79663. }
  79664. if (this._slerping && this._yawRange > Math.PI) {
  79665. //are we going to be crossing into the min/max region?
  79666. var boneFwd = BoneLookController._tmpVecs[8];
  79667. boneFwd.copyFrom(BABYLON.Axis.Z);
  79668. if (this._transformYawPitch) {
  79669. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79670. }
  79671. var boneRotMat = BoneLookController._tmpMats[4];
  79672. this._boneQuat.toRotationMatrix(boneRotMat);
  79673. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79674. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79675. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79676. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79677. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79678. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79679. if (angBtwTar > angBtwMidYaw) {
  79680. if (xzlen == null) {
  79681. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79682. }
  79683. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79684. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79685. if (angBtwMin < angBtwMax) {
  79686. newYaw = boneYaw + Math.PI * .75;
  79687. localTarget.z = Math.cos(newYaw) * xzlen;
  79688. localTarget.x = Math.sin(newYaw) * xzlen;
  79689. }
  79690. else {
  79691. newYaw = boneYaw - Math.PI * .75;
  79692. localTarget.z = Math.cos(newYaw) * xzlen;
  79693. localTarget.x = Math.sin(newYaw) * xzlen;
  79694. }
  79695. }
  79696. }
  79697. if (yaw != newYaw) {
  79698. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79699. localTarget.addInPlace(bonePos);
  79700. target = localTarget;
  79701. }
  79702. }
  79703. }
  79704. var zaxis = BoneLookController._tmpVecs[5];
  79705. var xaxis = BoneLookController._tmpVecs[6];
  79706. var yaxis = BoneLookController._tmpVecs[7];
  79707. var _tmpQuat = BoneLookController._tmpQuat;
  79708. target.subtractToRef(bonePos, zaxis);
  79709. zaxis.normalize();
  79710. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79711. xaxis.normalize();
  79712. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79713. yaxis.normalize();
  79714. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79715. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79716. return;
  79717. }
  79718. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79719. return;
  79720. }
  79721. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79722. return;
  79723. }
  79724. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79725. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79726. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79727. }
  79728. if (this.slerpAmount < 1) {
  79729. if (!this._slerping) {
  79730. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79731. }
  79732. if (this._transformYawPitch) {
  79733. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79734. }
  79735. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79736. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79737. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79738. this._slerping = true;
  79739. }
  79740. else {
  79741. if (this._transformYawPitch) {
  79742. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79743. }
  79744. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79745. this._slerping = false;
  79746. }
  79747. };
  79748. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79749. var angDiff = ang2 - ang1;
  79750. angDiff %= Math.PI * 2;
  79751. if (angDiff > Math.PI) {
  79752. angDiff -= Math.PI * 2;
  79753. }
  79754. else if (angDiff < -Math.PI) {
  79755. angDiff += Math.PI * 2;
  79756. }
  79757. return angDiff;
  79758. };
  79759. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79760. ang1 %= (2 * Math.PI);
  79761. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79762. ang2 %= (2 * Math.PI);
  79763. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79764. var ab = 0;
  79765. if (ang1 < ang2) {
  79766. ab = ang2 - ang1;
  79767. }
  79768. else {
  79769. ab = ang1 - ang2;
  79770. }
  79771. if (ab > Math.PI) {
  79772. ab = Math.PI * 2 - ab;
  79773. }
  79774. return ab;
  79775. };
  79776. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79777. ang %= (2 * Math.PI);
  79778. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79779. ang1 %= (2 * Math.PI);
  79780. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79781. ang2 %= (2 * Math.PI);
  79782. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79783. if (ang1 < ang2) {
  79784. if (ang > ang1 && ang < ang2) {
  79785. return true;
  79786. }
  79787. }
  79788. else {
  79789. if (ang > ang2 && ang < ang1) {
  79790. return true;
  79791. }
  79792. }
  79793. return false;
  79794. };
  79795. 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()];
  79796. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79797. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79798. return BoneLookController;
  79799. }());
  79800. BABYLON.BoneLookController = BoneLookController;
  79801. })(BABYLON || (BABYLON = {}));
  79802. //# sourceMappingURL=babylon.boneLookController.js.map
  79803. var BABYLON;
  79804. (function (BABYLON) {
  79805. /**
  79806. * Class used to handle skinning animations
  79807. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79808. */
  79809. var Skeleton = /** @class */ (function () {
  79810. /**
  79811. * Creates a new skeleton
  79812. * @param name defines the skeleton name
  79813. * @param id defines the skeleton Id
  79814. * @param scene defines the hosting scene
  79815. */
  79816. function Skeleton(
  79817. /** defines the skeleton name */
  79818. name,
  79819. /** defines the skeleton Id */
  79820. id, scene) {
  79821. this.name = name;
  79822. this.id = id;
  79823. /**
  79824. * Gets the list of child bones
  79825. */
  79826. this.bones = new Array();
  79827. /**
  79828. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79829. */
  79830. this.needInitialSkinMatrix = false;
  79831. this._isDirty = true;
  79832. this._meshesWithPoseMatrix = new Array();
  79833. this._identity = BABYLON.Matrix.Identity();
  79834. this._ranges = {};
  79835. this._lastAbsoluteTransformsUpdateId = -1;
  79836. /**
  79837. * Specifies if the skeleton should be serialized
  79838. */
  79839. this.doNotSerialize = false;
  79840. this._animationPropertiesOverride = null;
  79841. // Events
  79842. /**
  79843. * An observable triggered before computing the skeleton's matrices
  79844. */
  79845. this.onBeforeComputeObservable = new BABYLON.Observable();
  79846. this.bones = [];
  79847. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79848. scene.skeletons.push(this);
  79849. //make sure it will recalculate the matrix next time prepare is called.
  79850. this._isDirty = true;
  79851. }
  79852. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79853. /**
  79854. * Gets or sets the animation properties override
  79855. */
  79856. get: function () {
  79857. if (!this._animationPropertiesOverride) {
  79858. return this._scene.animationPropertiesOverride;
  79859. }
  79860. return this._animationPropertiesOverride;
  79861. },
  79862. set: function (value) {
  79863. this._animationPropertiesOverride = value;
  79864. },
  79865. enumerable: true,
  79866. configurable: true
  79867. });
  79868. // Members
  79869. /**
  79870. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79871. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79872. * @returns a Float32Array containing matrices data
  79873. */
  79874. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79875. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79876. return mesh._bonesTransformMatrices;
  79877. }
  79878. if (!this._transformMatrices) {
  79879. this.prepare();
  79880. }
  79881. return this._transformMatrices;
  79882. };
  79883. /**
  79884. * Gets the current hosting scene
  79885. * @returns a scene object
  79886. */
  79887. Skeleton.prototype.getScene = function () {
  79888. return this._scene;
  79889. };
  79890. // Methods
  79891. /**
  79892. * Gets a string representing the current skeleton data
  79893. * @param fullDetails defines a boolean indicating if we want a verbose version
  79894. * @returns a string representing the current skeleton data
  79895. */
  79896. Skeleton.prototype.toString = function (fullDetails) {
  79897. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79898. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79899. if (fullDetails) {
  79900. ret += ", Ranges: {";
  79901. var first = true;
  79902. for (var name_1 in this._ranges) {
  79903. if (first) {
  79904. ret += ", ";
  79905. first = false;
  79906. }
  79907. ret += name_1;
  79908. }
  79909. ret += "}";
  79910. }
  79911. return ret;
  79912. };
  79913. /**
  79914. * Get bone's index searching by name
  79915. * @param name defines bone's name to search for
  79916. * @return the indice of the bone. Returns -1 if not found
  79917. */
  79918. Skeleton.prototype.getBoneIndexByName = function (name) {
  79919. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79920. if (this.bones[boneIndex].name === name) {
  79921. return boneIndex;
  79922. }
  79923. }
  79924. return -1;
  79925. };
  79926. /**
  79927. * Creater a new animation range
  79928. * @param name defines the name of the range
  79929. * @param from defines the start key
  79930. * @param to defines the end key
  79931. */
  79932. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79933. // check name not already in use
  79934. if (!this._ranges[name]) {
  79935. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79936. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79937. if (this.bones[i].animations[0]) {
  79938. this.bones[i].animations[0].createRange(name, from, to);
  79939. }
  79940. }
  79941. }
  79942. };
  79943. /**
  79944. * Delete a specific animation range
  79945. * @param name defines the name of the range
  79946. * @param deleteFrames defines if frames must be removed as well
  79947. */
  79948. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79949. if (deleteFrames === void 0) { deleteFrames = true; }
  79950. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79951. if (this.bones[i].animations[0]) {
  79952. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79953. }
  79954. }
  79955. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79956. };
  79957. /**
  79958. * Gets a specific animation range
  79959. * @param name defines the name of the range to look for
  79960. * @returns the requested animation range or null if not found
  79961. */
  79962. Skeleton.prototype.getAnimationRange = function (name) {
  79963. return this._ranges[name];
  79964. };
  79965. /**
  79966. * Gets the list of all animation ranges defined on this skeleton
  79967. * @returns an array
  79968. */
  79969. Skeleton.prototype.getAnimationRanges = function () {
  79970. var animationRanges = [];
  79971. var name;
  79972. var i = 0;
  79973. for (name in this._ranges) {
  79974. animationRanges[i] = this._ranges[name];
  79975. i++;
  79976. }
  79977. return animationRanges;
  79978. };
  79979. /**
  79980. * Copy animation range from a source skeleton.
  79981. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79982. * @param source defines the source skeleton
  79983. * @param name defines the name of the range to copy
  79984. * @param rescaleAsRequired defines if rescaling must be applied if required
  79985. * @returns true if operation was successful
  79986. */
  79987. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79988. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79989. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79990. return false;
  79991. }
  79992. var ret = true;
  79993. var frameOffset = this._getHighestAnimationFrame() + 1;
  79994. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79995. var boneDict = {};
  79996. var sourceBones = source.bones;
  79997. var nBones;
  79998. var i;
  79999. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80000. boneDict[sourceBones[i].name] = sourceBones[i];
  80001. }
  80002. if (this.bones.length !== sourceBones.length) {
  80003. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80004. ret = false;
  80005. }
  80006. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80007. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80008. var boneName = this.bones[i].name;
  80009. var sourceBone = boneDict[boneName];
  80010. if (sourceBone) {
  80011. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80012. }
  80013. else {
  80014. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80015. ret = false;
  80016. }
  80017. }
  80018. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80019. var range = source.getAnimationRange(name);
  80020. if (range) {
  80021. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80022. }
  80023. return ret;
  80024. };
  80025. /**
  80026. * Forces the skeleton to go to rest pose
  80027. */
  80028. Skeleton.prototype.returnToRest = function () {
  80029. for (var index = 0; index < this.bones.length; index++) {
  80030. this.bones[index].returnToRest();
  80031. }
  80032. };
  80033. Skeleton.prototype._getHighestAnimationFrame = function () {
  80034. var ret = 0;
  80035. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80036. if (this.bones[i].animations[0]) {
  80037. var highest = this.bones[i].animations[0].getHighestFrame();
  80038. if (ret < highest) {
  80039. ret = highest;
  80040. }
  80041. }
  80042. }
  80043. return ret;
  80044. };
  80045. /**
  80046. * Begin a specific animation range
  80047. * @param name defines the name of the range to start
  80048. * @param loop defines if looping must be turned on (false by default)
  80049. * @param speedRatio defines the speed ratio to apply (1 by default)
  80050. * @param onAnimationEnd defines a callback which will be called when animation will end
  80051. * @returns a new animatable
  80052. */
  80053. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80054. var range = this.getAnimationRange(name);
  80055. if (!range) {
  80056. return null;
  80057. }
  80058. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80059. };
  80060. /** @hidden */
  80061. Skeleton.prototype._markAsDirty = function () {
  80062. this._isDirty = true;
  80063. };
  80064. /** @hidden */
  80065. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80066. this._meshesWithPoseMatrix.push(mesh);
  80067. };
  80068. /** @hidden */
  80069. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80070. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80071. if (index > -1) {
  80072. this._meshesWithPoseMatrix.splice(index, 1);
  80073. }
  80074. };
  80075. /** @hidden */
  80076. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80077. this.onBeforeComputeObservable.notifyObservers(this);
  80078. for (var index = 0; index < this.bones.length; index++) {
  80079. var bone = this.bones[index];
  80080. var parentBone = bone.getParent();
  80081. if (parentBone) {
  80082. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80083. }
  80084. else {
  80085. if (initialSkinMatrix) {
  80086. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80087. }
  80088. else {
  80089. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80090. }
  80091. }
  80092. if (bone._index !== -1) {
  80093. var mappedIndex = bone._index === null ? index : bone._index;
  80094. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80095. }
  80096. }
  80097. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80098. };
  80099. /**
  80100. * Build all resources required to render a skeleton
  80101. */
  80102. Skeleton.prototype.prepare = function () {
  80103. if (!this._isDirty) {
  80104. return;
  80105. }
  80106. if (this.needInitialSkinMatrix) {
  80107. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80108. var mesh = this._meshesWithPoseMatrix[index];
  80109. var poseMatrix = mesh.getPoseMatrix();
  80110. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80111. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80112. }
  80113. if (this._synchronizedWithMesh !== mesh) {
  80114. this._synchronizedWithMesh = mesh;
  80115. // Prepare bones
  80116. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80117. var bone = this.bones[boneIndex];
  80118. if (!bone.getParent()) {
  80119. var matrix = bone.getBaseMatrix();
  80120. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80121. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80122. }
  80123. }
  80124. }
  80125. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80126. }
  80127. }
  80128. else {
  80129. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80130. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80131. }
  80132. this._computeTransformMatrices(this._transformMatrices, null);
  80133. }
  80134. this._isDirty = false;
  80135. this._scene._activeBones.addCount(this.bones.length, false);
  80136. };
  80137. /**
  80138. * Gets the list of animatables currently running for this skeleton
  80139. * @returns an array of animatables
  80140. */
  80141. Skeleton.prototype.getAnimatables = function () {
  80142. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80143. this._animatables = [];
  80144. for (var index = 0; index < this.bones.length; index++) {
  80145. this._animatables.push(this.bones[index]);
  80146. }
  80147. }
  80148. return this._animatables;
  80149. };
  80150. /**
  80151. * Clone the current skeleton
  80152. * @param name defines the name of the new skeleton
  80153. * @param id defines the id of the enw skeleton
  80154. * @returns the new skeleton
  80155. */
  80156. Skeleton.prototype.clone = function (name, id) {
  80157. var result = new Skeleton(name, id || name, this._scene);
  80158. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80159. for (var index = 0; index < this.bones.length; index++) {
  80160. var source = this.bones[index];
  80161. var parentBone = null;
  80162. var parent_1 = source.getParent();
  80163. if (parent_1) {
  80164. var parentIndex = this.bones.indexOf(parent_1);
  80165. parentBone = result.bones[parentIndex];
  80166. }
  80167. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80168. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80169. }
  80170. if (this._ranges) {
  80171. result._ranges = {};
  80172. for (var rangeName in this._ranges) {
  80173. var range = this._ranges[rangeName];
  80174. if (range) {
  80175. result._ranges[rangeName] = range.clone();
  80176. }
  80177. }
  80178. }
  80179. this._isDirty = true;
  80180. return result;
  80181. };
  80182. /**
  80183. * Enable animation blending for this skeleton
  80184. * @param blendingSpeed defines the blending speed to apply
  80185. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80186. */
  80187. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80188. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80189. this.bones.forEach(function (bone) {
  80190. bone.animations.forEach(function (animation) {
  80191. animation.enableBlending = true;
  80192. animation.blendingSpeed = blendingSpeed;
  80193. });
  80194. });
  80195. };
  80196. /**
  80197. * Releases all resources associated with the current skeleton
  80198. */
  80199. Skeleton.prototype.dispose = function () {
  80200. this._meshesWithPoseMatrix = [];
  80201. // Animations
  80202. this.getScene().stopAnimation(this);
  80203. // Remove from scene
  80204. this.getScene().removeSkeleton(this);
  80205. };
  80206. /**
  80207. * Serialize the skeleton in a JSON object
  80208. * @returns a JSON object
  80209. */
  80210. Skeleton.prototype.serialize = function () {
  80211. var serializationObject = {};
  80212. serializationObject.name = this.name;
  80213. serializationObject.id = this.id;
  80214. if (this.dimensionsAtRest) {
  80215. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80216. }
  80217. serializationObject.bones = [];
  80218. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80219. for (var index = 0; index < this.bones.length; index++) {
  80220. var bone = this.bones[index];
  80221. var parent_2 = bone.getParent();
  80222. var serializedBone = {
  80223. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80224. name: bone.name,
  80225. matrix: bone.getBaseMatrix().toArray(),
  80226. rest: bone.getRestPose().toArray()
  80227. };
  80228. serializationObject.bones.push(serializedBone);
  80229. if (bone.length) {
  80230. serializedBone.length = bone.length;
  80231. }
  80232. if (bone.metadata) {
  80233. serializedBone.metadata = bone.metadata;
  80234. }
  80235. if (bone.animations && bone.animations.length > 0) {
  80236. serializedBone.animation = bone.animations[0].serialize();
  80237. }
  80238. serializationObject.ranges = [];
  80239. for (var name in this._ranges) {
  80240. var source = this._ranges[name];
  80241. if (!source) {
  80242. continue;
  80243. }
  80244. var range = {};
  80245. range.name = name;
  80246. range.from = source.from;
  80247. range.to = source.to;
  80248. serializationObject.ranges.push(range);
  80249. }
  80250. }
  80251. return serializationObject;
  80252. };
  80253. /**
  80254. * Creates a new skeleton from serialized data
  80255. * @param parsedSkeleton defines the serialized data
  80256. * @param scene defines the hosting scene
  80257. * @returns a new skeleton
  80258. */
  80259. Skeleton.Parse = function (parsedSkeleton, scene) {
  80260. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80261. if (parsedSkeleton.dimensionsAtRest) {
  80262. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80263. }
  80264. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80265. var index;
  80266. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80267. var parsedBone = parsedSkeleton.bones[index];
  80268. var parentBone = null;
  80269. if (parsedBone.parentBoneIndex > -1) {
  80270. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80271. }
  80272. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80273. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80274. if (parsedBone.length) {
  80275. bone.length = parsedBone.length;
  80276. }
  80277. if (parsedBone.metadata) {
  80278. bone.metadata = parsedBone.metadata;
  80279. }
  80280. if (parsedBone.animation) {
  80281. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80282. }
  80283. }
  80284. // placed after bones, so createAnimationRange can cascade down
  80285. if (parsedSkeleton.ranges) {
  80286. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80287. var data = parsedSkeleton.ranges[index];
  80288. skeleton.createAnimationRange(data.name, data.from, data.to);
  80289. }
  80290. }
  80291. return skeleton;
  80292. };
  80293. /**
  80294. * Compute all node absolute transforms
  80295. * @param forceUpdate defines if computation must be done even if cache is up to date
  80296. */
  80297. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80298. if (forceUpdate === void 0) { forceUpdate = false; }
  80299. var renderId = this._scene.getRenderId();
  80300. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80301. this.bones[0].computeAbsoluteTransforms();
  80302. this._lastAbsoluteTransformsUpdateId = renderId;
  80303. }
  80304. };
  80305. /**
  80306. * Gets the root pose matrix
  80307. * @returns a matrix
  80308. */
  80309. Skeleton.prototype.getPoseMatrix = function () {
  80310. var poseMatrix = null;
  80311. if (this._meshesWithPoseMatrix.length > 0) {
  80312. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80313. }
  80314. return poseMatrix;
  80315. };
  80316. /**
  80317. * Sorts bones per internal index
  80318. */
  80319. Skeleton.prototype.sortBones = function () {
  80320. var bones = new Array();
  80321. var visited = new Array(this.bones.length);
  80322. for (var index = 0; index < this.bones.length; index++) {
  80323. this._sortBones(index, bones, visited);
  80324. }
  80325. this.bones = bones;
  80326. };
  80327. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80328. if (visited[index]) {
  80329. return;
  80330. }
  80331. visited[index] = true;
  80332. var bone = this.bones[index];
  80333. if (bone._index === undefined) {
  80334. bone._index = index;
  80335. }
  80336. var parentBone = bone.getParent();
  80337. if (parentBone) {
  80338. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80339. }
  80340. bones.push(bone);
  80341. };
  80342. return Skeleton;
  80343. }());
  80344. BABYLON.Skeleton = Skeleton;
  80345. })(BABYLON || (BABYLON = {}));
  80346. //# sourceMappingURL=babylon.skeleton.js.map
  80347. var BABYLON;
  80348. (function (BABYLON) {
  80349. var SphericalPolynomial = /** @class */ (function () {
  80350. function SphericalPolynomial() {
  80351. this.x = BABYLON.Vector3.Zero();
  80352. this.y = BABYLON.Vector3.Zero();
  80353. this.z = BABYLON.Vector3.Zero();
  80354. this.xx = BABYLON.Vector3.Zero();
  80355. this.yy = BABYLON.Vector3.Zero();
  80356. this.zz = BABYLON.Vector3.Zero();
  80357. this.xy = BABYLON.Vector3.Zero();
  80358. this.yz = BABYLON.Vector3.Zero();
  80359. this.zx = BABYLON.Vector3.Zero();
  80360. }
  80361. SphericalPolynomial.prototype.addAmbient = function (color) {
  80362. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80363. this.xx = this.xx.add(colorVector);
  80364. this.yy = this.yy.add(colorVector);
  80365. this.zz = this.zz.add(colorVector);
  80366. };
  80367. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80368. var result = new SphericalPolynomial();
  80369. result.x = harmonics.L11.scale(1.02333);
  80370. result.y = harmonics.L1_1.scale(1.02333);
  80371. result.z = harmonics.L10.scale(1.02333);
  80372. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80373. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80374. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80375. result.yz = harmonics.L2_1.scale(0.858086);
  80376. result.zx = harmonics.L21.scale(0.858086);
  80377. result.xy = harmonics.L2_2.scale(0.858086);
  80378. result.scale(1.0 / Math.PI);
  80379. return result;
  80380. };
  80381. SphericalPolynomial.prototype.scale = function (scale) {
  80382. this.x = this.x.scale(scale);
  80383. this.y = this.y.scale(scale);
  80384. this.z = this.z.scale(scale);
  80385. this.xx = this.xx.scale(scale);
  80386. this.yy = this.yy.scale(scale);
  80387. this.zz = this.zz.scale(scale);
  80388. this.yz = this.yz.scale(scale);
  80389. this.zx = this.zx.scale(scale);
  80390. this.xy = this.xy.scale(scale);
  80391. };
  80392. return SphericalPolynomial;
  80393. }());
  80394. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80395. var SphericalHarmonics = /** @class */ (function () {
  80396. function SphericalHarmonics() {
  80397. this.L00 = BABYLON.Vector3.Zero();
  80398. this.L1_1 = BABYLON.Vector3.Zero();
  80399. this.L10 = BABYLON.Vector3.Zero();
  80400. this.L11 = BABYLON.Vector3.Zero();
  80401. this.L2_2 = BABYLON.Vector3.Zero();
  80402. this.L2_1 = BABYLON.Vector3.Zero();
  80403. this.L20 = BABYLON.Vector3.Zero();
  80404. this.L21 = BABYLON.Vector3.Zero();
  80405. this.L22 = BABYLON.Vector3.Zero();
  80406. }
  80407. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80408. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80409. var c = colorVector.scale(deltaSolidAngle);
  80410. this.L00 = this.L00.add(c.scale(0.282095));
  80411. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80412. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80413. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80414. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80415. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80416. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80417. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80418. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80419. };
  80420. SphericalHarmonics.prototype.scale = function (scale) {
  80421. this.L00 = this.L00.scale(scale);
  80422. this.L1_1 = this.L1_1.scale(scale);
  80423. this.L10 = this.L10.scale(scale);
  80424. this.L11 = this.L11.scale(scale);
  80425. this.L2_2 = this.L2_2.scale(scale);
  80426. this.L2_1 = this.L2_1.scale(scale);
  80427. this.L20 = this.L20.scale(scale);
  80428. this.L21 = this.L21.scale(scale);
  80429. this.L22 = this.L22.scale(scale);
  80430. };
  80431. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80432. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80433. //
  80434. // E_lm = A_l * L_lm
  80435. //
  80436. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80437. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80438. // the scaling factors are given in equation 9.
  80439. // Constant (Band 0)
  80440. this.L00 = this.L00.scale(3.141593);
  80441. // Linear (Band 1)
  80442. this.L1_1 = this.L1_1.scale(2.094395);
  80443. this.L10 = this.L10.scale(2.094395);
  80444. this.L11 = this.L11.scale(2.094395);
  80445. // Quadratic (Band 2)
  80446. this.L2_2 = this.L2_2.scale(0.785398);
  80447. this.L2_1 = this.L2_1.scale(0.785398);
  80448. this.L20 = this.L20.scale(0.785398);
  80449. this.L21 = this.L21.scale(0.785398);
  80450. this.L22 = this.L22.scale(0.785398);
  80451. };
  80452. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80453. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80454. // L = (1/pi) * E * rho
  80455. //
  80456. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80457. this.scale(1.0 / Math.PI);
  80458. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80459. // (The pixel shader must apply albedo after texture fetches, etc).
  80460. };
  80461. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80462. var result = new SphericalHarmonics();
  80463. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80464. result.L1_1 = polynomial.y.scale(0.977204);
  80465. result.L10 = polynomial.z.scale(0.977204);
  80466. result.L11 = polynomial.x.scale(0.977204);
  80467. result.L2_2 = polynomial.xy.scale(1.16538);
  80468. result.L2_1 = polynomial.yz.scale(1.16538);
  80469. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80470. result.L21 = polynomial.zx.scale(1.16538);
  80471. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80472. result.scale(Math.PI);
  80473. return result;
  80474. };
  80475. return SphericalHarmonics;
  80476. }());
  80477. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80478. })(BABYLON || (BABYLON = {}));
  80479. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80480. var BABYLON;
  80481. (function (BABYLON) {
  80482. var FileFaceOrientation = /** @class */ (function () {
  80483. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80484. this.name = name;
  80485. this.worldAxisForNormal = worldAxisForNormal;
  80486. this.worldAxisForFileX = worldAxisForFileX;
  80487. this.worldAxisForFileY = worldAxisForFileY;
  80488. }
  80489. return FileFaceOrientation;
  80490. }());
  80491. ;
  80492. /**
  80493. * Helper class dealing with the extraction of spherical polynomial dataArray
  80494. * from a cube map.
  80495. */
  80496. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80497. function CubeMapToSphericalPolynomialTools() {
  80498. }
  80499. /**
  80500. * Converts a texture to the according Spherical Polynomial data.
  80501. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80502. *
  80503. * @param texture The texture to extract the information from.
  80504. * @return The Spherical Polynomial data.
  80505. */
  80506. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80507. if (!texture.isCube) {
  80508. // Only supports cube Textures currently.
  80509. return null;
  80510. }
  80511. var size = texture.getSize().width;
  80512. var right = texture.readPixels(0);
  80513. var left = texture.readPixels(1);
  80514. var up;
  80515. var down;
  80516. if (texture.isRenderTarget) {
  80517. up = texture.readPixels(3);
  80518. down = texture.readPixels(2);
  80519. }
  80520. else {
  80521. up = texture.readPixels(2);
  80522. down = texture.readPixels(3);
  80523. }
  80524. var front = texture.readPixels(4);
  80525. var back = texture.readPixels(5);
  80526. var gammaSpace = texture.gammaSpace;
  80527. // Always read as RGBA.
  80528. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80529. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80530. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80531. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80532. }
  80533. var cubeInfo = {
  80534. size: size,
  80535. right: right,
  80536. left: left,
  80537. up: up,
  80538. down: down,
  80539. front: front,
  80540. back: back,
  80541. format: format,
  80542. type: type,
  80543. gammaSpace: gammaSpace,
  80544. };
  80545. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80546. };
  80547. /**
  80548. * Converts a cubemap to the according Spherical Polynomial data.
  80549. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80550. *
  80551. * @param cubeInfo The Cube map to extract the information from.
  80552. * @return The Spherical Polynomial data.
  80553. */
  80554. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80555. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80556. var totalSolidAngle = 0.0;
  80557. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80558. var du = 2.0 / cubeInfo.size;
  80559. var dv = du;
  80560. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80561. var minUV = du * 0.5 - 1.0;
  80562. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80563. var fileFace = this.FileFaces[faceIndex];
  80564. var dataArray = cubeInfo[fileFace.name];
  80565. var v = minUV;
  80566. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80567. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80568. // Because SP is still linear, so summation is fine in that basis.
  80569. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80570. for (var y = 0; y < cubeInfo.size; y++) {
  80571. var u = minUV;
  80572. for (var x = 0; x < cubeInfo.size; x++) {
  80573. // World direction (not normalised)
  80574. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80575. worldDirection.normalize();
  80576. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80577. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80578. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80579. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80580. // Handle Integer types.
  80581. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80582. r /= 255;
  80583. g /= 255;
  80584. b /= 255;
  80585. }
  80586. // Handle Gamma space textures.
  80587. if (cubeInfo.gammaSpace) {
  80588. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80589. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80590. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80591. }
  80592. var color = new BABYLON.Color3(r, g, b);
  80593. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80594. totalSolidAngle += deltaSolidAngle;
  80595. u += du;
  80596. }
  80597. v += dv;
  80598. }
  80599. }
  80600. // Solid angle for entire sphere is 4*pi
  80601. var sphereSolidAngle = 4.0 * Math.PI;
  80602. // Adjust the solid angle to allow for how many faces we processed.
  80603. var facesProcessed = 6.0;
  80604. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80605. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80606. // This is needed because the numerical integration over the cube uses a
  80607. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80608. // and also to compensate for accumulative error due to float precision in the summation.
  80609. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80610. sphericalHarmonics.scale(correctionFactor);
  80611. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80612. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80613. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80614. };
  80615. CubeMapToSphericalPolynomialTools.FileFaces = [
  80616. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80617. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80618. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80619. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80620. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80621. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80622. ];
  80623. return CubeMapToSphericalPolynomialTools;
  80624. }());
  80625. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80626. })(BABYLON || (BABYLON = {}));
  80627. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80628. var BABYLON;
  80629. (function (BABYLON) {
  80630. /**
  80631. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80632. */
  80633. var PanoramaToCubeMapTools = /** @class */ (function () {
  80634. function PanoramaToCubeMapTools() {
  80635. }
  80636. /**
  80637. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80638. *
  80639. * @param float32Array The source data.
  80640. * @param inputWidth The width of the input panorama.
  80641. * @param inputhHeight The height of the input panorama.
  80642. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80643. * @return The cubemap data
  80644. */
  80645. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80646. if (!float32Array) {
  80647. throw "ConvertPanoramaToCubemap: input cannot be null";
  80648. }
  80649. if (float32Array.length != inputWidth * inputHeight * 3) {
  80650. throw "ConvertPanoramaToCubemap: input size is wrong";
  80651. }
  80652. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80653. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80654. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80655. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80656. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80657. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80658. return {
  80659. front: textureFront,
  80660. back: textureBack,
  80661. left: textureLeft,
  80662. right: textureRight,
  80663. up: textureUp,
  80664. down: textureDown,
  80665. size: size,
  80666. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80667. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80668. gammaSpace: false,
  80669. };
  80670. };
  80671. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80672. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80673. var textureArray = new Float32Array(buffer);
  80674. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80675. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80676. var dy = 1 / texSize;
  80677. var fy = 0;
  80678. for (var y = 0; y < texSize; y++) {
  80679. var xv1 = faceData[0];
  80680. var xv2 = faceData[2];
  80681. for (var x = 0; x < texSize; x++) {
  80682. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80683. v.normalize();
  80684. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80685. // 3 channels per pixels
  80686. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80687. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80688. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80689. xv1 = xv1.add(rotDX1);
  80690. xv2 = xv2.add(rotDX2);
  80691. }
  80692. fy += dy;
  80693. }
  80694. return textureArray;
  80695. };
  80696. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80697. var theta = Math.atan2(vDir.z, vDir.x);
  80698. var phi = Math.acos(vDir.y);
  80699. while (theta < -Math.PI)
  80700. theta += 2 * Math.PI;
  80701. while (theta > Math.PI)
  80702. theta -= 2 * Math.PI;
  80703. var dx = theta / Math.PI;
  80704. var dy = phi / Math.PI;
  80705. // recenter.
  80706. dx = dx * 0.5 + 0.5;
  80707. var px = Math.round(dx * inputWidth);
  80708. if (px < 0)
  80709. px = 0;
  80710. else if (px >= inputWidth)
  80711. px = inputWidth - 1;
  80712. var py = Math.round(dy * inputHeight);
  80713. if (py < 0)
  80714. py = 0;
  80715. else if (py >= inputHeight)
  80716. py = inputHeight - 1;
  80717. var inputY = (inputHeight - py - 1);
  80718. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80719. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80720. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80721. return {
  80722. r: r,
  80723. g: g,
  80724. b: b
  80725. };
  80726. };
  80727. PanoramaToCubeMapTools.FACE_FRONT = [
  80728. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80729. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80730. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80731. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80732. ];
  80733. PanoramaToCubeMapTools.FACE_BACK = [
  80734. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80735. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80736. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80737. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80738. ];
  80739. PanoramaToCubeMapTools.FACE_RIGHT = [
  80740. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80741. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80742. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80743. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80744. ];
  80745. PanoramaToCubeMapTools.FACE_LEFT = [
  80746. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80747. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80748. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80749. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80750. ];
  80751. PanoramaToCubeMapTools.FACE_DOWN = [
  80752. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80753. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80754. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80755. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80756. ];
  80757. PanoramaToCubeMapTools.FACE_UP = [
  80758. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80759. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80760. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80761. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80762. ];
  80763. return PanoramaToCubeMapTools;
  80764. }());
  80765. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80766. })(BABYLON || (BABYLON = {}));
  80767. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80768. var BABYLON;
  80769. (function (BABYLON) {
  80770. ;
  80771. /**
  80772. * This groups tools to convert HDR texture to native colors array.
  80773. */
  80774. var HDRTools = /** @class */ (function () {
  80775. function HDRTools() {
  80776. }
  80777. HDRTools.Ldexp = function (mantissa, exponent) {
  80778. if (exponent > 1023) {
  80779. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80780. }
  80781. if (exponent < -1074) {
  80782. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80783. }
  80784. return mantissa * Math.pow(2, exponent);
  80785. };
  80786. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80787. if (exponent > 0) { /*nonzero pixel*/
  80788. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80789. float32array[index + 0] = red * exponent;
  80790. float32array[index + 1] = green * exponent;
  80791. float32array[index + 2] = blue * exponent;
  80792. }
  80793. else {
  80794. float32array[index + 0] = 0;
  80795. float32array[index + 1] = 0;
  80796. float32array[index + 2] = 0;
  80797. }
  80798. };
  80799. HDRTools.readStringLine = function (uint8array, startIndex) {
  80800. var line = "";
  80801. var character = "";
  80802. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80803. character = String.fromCharCode(uint8array[i]);
  80804. if (character == "\n") {
  80805. break;
  80806. }
  80807. line += character;
  80808. }
  80809. return line;
  80810. };
  80811. /**
  80812. * Reads header information from an RGBE texture stored in a native array.
  80813. * More information on this format are available here:
  80814. * https://en.wikipedia.org/wiki/RGBE_image_format
  80815. *
  80816. * @param uint8array The binary file stored in native array.
  80817. * @return The header information.
  80818. */
  80819. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80820. var height = 0;
  80821. var width = 0;
  80822. var line = this.readStringLine(uint8array, 0);
  80823. if (line[0] != '#' || line[1] != '?') {
  80824. throw "Bad HDR Format.";
  80825. }
  80826. var endOfHeader = false;
  80827. var findFormat = false;
  80828. var lineIndex = 0;
  80829. do {
  80830. lineIndex += (line.length + 1);
  80831. line = this.readStringLine(uint8array, lineIndex);
  80832. if (line == "FORMAT=32-bit_rle_rgbe") {
  80833. findFormat = true;
  80834. }
  80835. else if (line.length == 0) {
  80836. endOfHeader = true;
  80837. }
  80838. } while (!endOfHeader);
  80839. if (!findFormat) {
  80840. throw "HDR Bad header format, unsupported FORMAT";
  80841. }
  80842. lineIndex += (line.length + 1);
  80843. line = this.readStringLine(uint8array, lineIndex);
  80844. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80845. var match = sizeRegexp.exec(line);
  80846. // TODO. Support +Y and -X if needed.
  80847. if (!match || match.length < 3) {
  80848. throw "HDR Bad header format, no size";
  80849. }
  80850. width = parseInt(match[2]);
  80851. height = parseInt(match[1]);
  80852. if (width < 8 || width > 0x7fff) {
  80853. throw "HDR Bad header format, unsupported size";
  80854. }
  80855. lineIndex += (line.length + 1);
  80856. return {
  80857. height: height,
  80858. width: width,
  80859. dataPosition: lineIndex
  80860. };
  80861. };
  80862. /**
  80863. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80864. * This RGBE texture needs to store the information as a panorama.
  80865. *
  80866. * More information on this format are available here:
  80867. * https://en.wikipedia.org/wiki/RGBE_image_format
  80868. *
  80869. * @param buffer The binary file stored in an array buffer.
  80870. * @param size The expected size of the extracted cubemap.
  80871. * @return The Cube Map information.
  80872. */
  80873. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80874. var uint8array = new Uint8Array(buffer);
  80875. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80876. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80877. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80878. return cubeMapData;
  80879. };
  80880. /**
  80881. * Returns the pixels data extracted from an RGBE texture.
  80882. * This pixels will be stored left to right up to down in the R G B order in one array.
  80883. *
  80884. * More information on this format are available here:
  80885. * https://en.wikipedia.org/wiki/RGBE_image_format
  80886. *
  80887. * @param uint8array The binary file stored in an array buffer.
  80888. * @param hdrInfo The header information of the file.
  80889. * @return The pixels data in RGB right to left up to down order.
  80890. */
  80891. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80892. // Keep for multi format supports.
  80893. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80894. };
  80895. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80896. var num_scanlines = hdrInfo.height;
  80897. var scanline_width = hdrInfo.width;
  80898. var a, b, c, d, count;
  80899. var dataIndex = hdrInfo.dataPosition;
  80900. var index = 0, endIndex = 0, i = 0;
  80901. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80902. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80903. // 3 channels of 4 bytes per pixel in float.
  80904. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80905. var resultArray = new Float32Array(resultBuffer);
  80906. // read in each successive scanline
  80907. while (num_scanlines > 0) {
  80908. a = uint8array[dataIndex++];
  80909. b = uint8array[dataIndex++];
  80910. c = uint8array[dataIndex++];
  80911. d = uint8array[dataIndex++];
  80912. if (a != 2 || b != 2 || (c & 0x80)) {
  80913. // this file is not run length encoded
  80914. throw "HDR Bad header format, not RLE";
  80915. }
  80916. if (((c << 8) | d) != scanline_width) {
  80917. throw "HDR Bad header format, wrong scan line width";
  80918. }
  80919. index = 0;
  80920. // read each of the four channels for the scanline into the buffer
  80921. for (i = 0; i < 4; i++) {
  80922. endIndex = (i + 1) * scanline_width;
  80923. while (index < endIndex) {
  80924. a = uint8array[dataIndex++];
  80925. b = uint8array[dataIndex++];
  80926. if (a > 128) {
  80927. // a run of the same value
  80928. count = a - 128;
  80929. if ((count == 0) || (count > endIndex - index)) {
  80930. throw "HDR Bad Format, bad scanline data (run)";
  80931. }
  80932. while (count-- > 0) {
  80933. scanLineArray[index++] = b;
  80934. }
  80935. }
  80936. else {
  80937. // a non-run
  80938. count = a;
  80939. if ((count == 0) || (count > endIndex - index)) {
  80940. throw "HDR Bad Format, bad scanline data (non-run)";
  80941. }
  80942. scanLineArray[index++] = b;
  80943. if (--count > 0) {
  80944. for (var j = 0; j < count; j++) {
  80945. scanLineArray[index++] = uint8array[dataIndex++];
  80946. }
  80947. }
  80948. }
  80949. }
  80950. }
  80951. // now convert data from buffer into floats
  80952. for (i = 0; i < scanline_width; i++) {
  80953. a = scanLineArray[i];
  80954. b = scanLineArray[i + scanline_width];
  80955. c = scanLineArray[i + 2 * scanline_width];
  80956. d = scanLineArray[i + 3 * scanline_width];
  80957. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80958. }
  80959. num_scanlines--;
  80960. }
  80961. return resultArray;
  80962. };
  80963. return HDRTools;
  80964. }());
  80965. BABYLON.HDRTools = HDRTools;
  80966. })(BABYLON || (BABYLON = {}));
  80967. //# sourceMappingURL=babylon.hdr.js.map
  80968. var BABYLON;
  80969. (function (BABYLON) {
  80970. /**
  80971. * Sets of helpers addressing the serialization and deserialization of environment texture
  80972. * stored in a BabylonJS env file.
  80973. * Those files are usually stored as .env files.
  80974. */
  80975. var EnvironmentTextureTools = /** @class */ (function () {
  80976. function EnvironmentTextureTools() {
  80977. }
  80978. /**
  80979. * Gets the environment info from an env file.
  80980. * @param data The array buffer containing the .env bytes.
  80981. * @returns the environment file info (the json header) if successfully parsed.
  80982. */
  80983. EnvironmentTextureTools.GetEnvInfo = function (data) {
  80984. var dataView = new DataView(data);
  80985. var pos = 0;
  80986. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  80987. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  80988. BABYLON.Tools.Error('Not a babylon environment map');
  80989. return null;
  80990. }
  80991. }
  80992. // Read json manifest - collect characters up to null terminator
  80993. var manifestString = '';
  80994. var charCode = 0x00;
  80995. while ((charCode = dataView.getUint8(pos++))) {
  80996. manifestString += String.fromCharCode(charCode);
  80997. }
  80998. var manifest = JSON.parse(manifestString);
  80999. if (manifest.specular) {
  81000. // Extend the header with the position of the payload.
  81001. manifest.specular.specularDataPosition = pos;
  81002. }
  81003. return manifest;
  81004. };
  81005. /**
  81006. * Creates an environment texture from a loaded cube texture.
  81007. * @param texture defines the cube texture to convert in env file
  81008. * @return a promise containing the environment data if succesfull.
  81009. */
  81010. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81011. var _this = this;
  81012. var internalTexture = texture.getInternalTexture();
  81013. if (!internalTexture) {
  81014. return Promise.reject("The cube texture is invalid.");
  81015. }
  81016. if (!texture._prefiltered) {
  81017. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81018. }
  81019. var engine = internalTexture.getEngine();
  81020. if (engine && engine.premultipliedAlpha) {
  81021. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option.");
  81022. }
  81023. var canvas = engine.getRenderingCanvas();
  81024. if (!canvas) {
  81025. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81026. }
  81027. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81028. if (!engine.getCaps().textureFloatRender) {
  81029. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81030. if (!engine.getCaps().textureHalfFloatRender) {
  81031. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81032. }
  81033. }
  81034. var cubeWidth = internalTexture.width;
  81035. var hostingScene = new BABYLON.Scene(engine);
  81036. var specularTextures = {};
  81037. var promises = [];
  81038. // Read and collect all mipmaps data from the cube.
  81039. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81040. mipmapsCount = Math.round(mipmapsCount);
  81041. var _loop_1 = function (i) {
  81042. var faceWidth = Math.pow(2, mipmapsCount - i);
  81043. var _loop_2 = function (face) {
  81044. var data = texture.readPixels(face, i);
  81045. // Creates a temp texture with the face data.
  81046. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81047. // And rgbdEncode them.
  81048. var promise = new Promise(function (resolve, reject) {
  81049. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  81050. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81051. rgbdPostProcess.onApply = function (effect) {
  81052. effect._bindTexture("textureSampler", tempTexture);
  81053. };
  81054. // As the process needs to happen on the main canvas, keep track of the current size
  81055. var currentW = engine.getRenderWidth();
  81056. var currentH = engine.getRenderHeight();
  81057. // Set the desired size for the texture
  81058. engine.setSize(faceWidth, faceWidth);
  81059. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81060. // Reading datas from WebGL
  81061. canvas.toBlob(function (blob) {
  81062. var fileReader = new FileReader();
  81063. fileReader.onload = function (event) {
  81064. var arrayBuffer = event.target.result;
  81065. specularTextures[i * 6 + face] = arrayBuffer;
  81066. resolve();
  81067. };
  81068. fileReader.readAsArrayBuffer(blob);
  81069. });
  81070. // Reapply the previous canvas size
  81071. engine.setSize(currentW, currentH);
  81072. });
  81073. });
  81074. promises.push(promise);
  81075. };
  81076. // All faces of the cube.
  81077. for (var face = 0; face < 6; face++) {
  81078. _loop_2(face);
  81079. }
  81080. };
  81081. for (var i = 0; i <= mipmapsCount; i++) {
  81082. _loop_1(i);
  81083. }
  81084. // Once all the textures haves been collected as RGBD stored in PNGs
  81085. return Promise.all(promises).then(function () {
  81086. // We can delete the hosting scene keeping track of all the creation objects
  81087. hostingScene.dispose();
  81088. // Creates the json header for the env texture
  81089. var info = {
  81090. version: 1,
  81091. width: cubeWidth,
  81092. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81093. specular: {
  81094. mipmaps: []
  81095. }
  81096. };
  81097. // Sets the specular image data information
  81098. var position = 0;
  81099. for (var i = 0; i <= mipmapsCount; i++) {
  81100. for (var face = 0; face < 6; face++) {
  81101. var byteLength = specularTextures[i * 6 + face].byteLength;
  81102. info.specular.mipmaps.push({
  81103. length: byteLength,
  81104. position: position
  81105. });
  81106. position += byteLength;
  81107. }
  81108. }
  81109. // Encode the JSON as an array buffer
  81110. var infoString = JSON.stringify(info);
  81111. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81112. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81113. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81114. infoView[i] = infoString.charCodeAt(i);
  81115. }
  81116. // Ends up with a null terminator for easier parsing
  81117. infoView[infoString.length] = 0x00;
  81118. // Computes the final required size and creates the storage
  81119. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81120. var finalBuffer = new ArrayBuffer(totalSize);
  81121. var finalBufferView = new Uint8Array(finalBuffer);
  81122. var dataView = new DataView(finalBuffer);
  81123. // Copy the magic bytes identifying the file in
  81124. var pos = 0;
  81125. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81126. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81127. }
  81128. // Add the json info
  81129. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81130. pos += infoBuffer.byteLength;
  81131. // Finally inserts the texture data
  81132. for (var i = 0; i <= mipmapsCount; i++) {
  81133. for (var face = 0; face < 6; face++) {
  81134. var dataBuffer = specularTextures[i * 6 + face];
  81135. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  81136. pos += dataBuffer.byteLength;
  81137. }
  81138. }
  81139. // Voila
  81140. return finalBuffer;
  81141. });
  81142. };
  81143. /**
  81144. * Creates a JSON representation of the spherical data.
  81145. * @param texture defines the texture containing the polynomials
  81146. * @return the JSON representation of the spherical info
  81147. */
  81148. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  81149. var polynmials = texture.sphericalPolynomial;
  81150. if (polynmials == null) {
  81151. return null;
  81152. }
  81153. return {
  81154. polynomials: true,
  81155. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  81156. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  81157. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  81158. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  81159. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  81160. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  81161. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  81162. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  81163. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  81164. };
  81165. };
  81166. /**
  81167. * Uploads the texture info contained in the env file to te GPU.
  81168. * @param texture defines the internal texture to upload to
  81169. * @param arrayBuffer defines the buffer cotaining the data to load
  81170. * @param info defines the texture info retrieved through the GetEnvInfo method
  81171. * @returns a promise
  81172. */
  81173. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  81174. if (info.version !== 1) {
  81175. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81176. }
  81177. var specularInfo = info.specular;
  81178. if (!specularInfo) {
  81179. // Nothing else parsed so far
  81180. return Promise.resolve();
  81181. }
  81182. // Double checks the enclosed info
  81183. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  81184. mipmapsCount = Math.round(mipmapsCount) + 1;
  81185. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  81186. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  81187. }
  81188. // Gets everything ready.
  81189. var engine = texture.getEngine();
  81190. var expandTexture = false;
  81191. var generateNonLODTextures = false;
  81192. var rgbdPostProcess = null;
  81193. var cubeRtt = null;
  81194. var lodTextures = null;
  81195. var caps = engine.getCaps();
  81196. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81197. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81198. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  81199. // Add extra process if texture lod is not supported
  81200. if (!caps.textureLOD) {
  81201. expandTexture = false;
  81202. generateNonLODTextures = true;
  81203. lodTextures = {};
  81204. }
  81205. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  81206. else if (engine.webGLVersion < 2) {
  81207. expandTexture = false;
  81208. }
  81209. // If half float available we can uncompress the texture
  81210. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  81211. expandTexture = true;
  81212. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81213. }
  81214. // If full float available we can uncompress the texture
  81215. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  81216. expandTexture = true;
  81217. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81218. }
  81219. // Expand the texture if possible
  81220. if (expandTexture) {
  81221. // Simply run through the decode PP
  81222. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  81223. texture._isRGBD = false;
  81224. texture.invertY = false;
  81225. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  81226. generateDepthBuffer: false,
  81227. generateMipMaps: true,
  81228. generateStencilBuffer: false,
  81229. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  81230. type: texture.type,
  81231. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  81232. });
  81233. }
  81234. else {
  81235. texture._isRGBD = true;
  81236. texture.invertY = true;
  81237. // In case of missing support, applies the same patch than DDS files.
  81238. if (generateNonLODTextures) {
  81239. var mipSlices = 3;
  81240. var scale = texture._lodGenerationScale;
  81241. var offset = texture._lodGenerationOffset;
  81242. for (var i = 0; i < mipSlices; i++) {
  81243. //compute LOD from even spacing in smoothness (matching shader calculation)
  81244. var smoothness = i / (mipSlices - 1);
  81245. var roughness = 1 - smoothness;
  81246. var minLODIndex = offset; // roughness = 0
  81247. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  81248. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  81249. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  81250. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  81251. glTextureFromLod.isCube = true;
  81252. glTextureFromLod.invertY = true;
  81253. glTextureFromLod.generateMipMaps = false;
  81254. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  81255. // Wrap in a base texture for easy binding.
  81256. var lodTexture = new BABYLON.BaseTexture(null);
  81257. lodTexture.isCube = true;
  81258. lodTexture._texture = glTextureFromLod;
  81259. lodTextures[mipmapIndex] = lodTexture;
  81260. switch (i) {
  81261. case 0:
  81262. texture._lodTextureLow = lodTexture;
  81263. break;
  81264. case 1:
  81265. texture._lodTextureMid = lodTexture;
  81266. break;
  81267. case 2:
  81268. texture._lodTextureHigh = lodTexture;
  81269. break;
  81270. }
  81271. }
  81272. }
  81273. }
  81274. var promises = [];
  81275. var _loop_3 = function (i) {
  81276. var _loop_4 = function (face) {
  81277. // Retrieves the face data
  81278. var imageData = specularInfo.mipmaps[i * 6 + face];
  81279. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  81280. // Constructs an image element from bytes
  81281. var blob = new Blob([bytes], { type: 'image/png' });
  81282. var url = URL.createObjectURL(blob);
  81283. var image = new Image();
  81284. image.src = url;
  81285. // Enqueue promise to upload to the texture.
  81286. var promise = new Promise(function (resolve, reject) {
  81287. ;
  81288. image.onload = function () {
  81289. if (expandTexture) {
  81290. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  81291. reject(message);
  81292. }, image);
  81293. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81294. // Uncompress the data to a RTT
  81295. rgbdPostProcess.onApply = function (effect) {
  81296. effect._bindTexture("textureSampler", tempTexture_1);
  81297. effect.setFloat2("scale", 1, 1);
  81298. };
  81299. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  81300. // Cleanup
  81301. engine.restoreDefaultFramebuffer();
  81302. tempTexture_1.dispose();
  81303. window.URL.revokeObjectURL(url);
  81304. resolve();
  81305. });
  81306. }
  81307. else {
  81308. engine._uploadImageToTexture(texture, face, i, image);
  81309. // Upload the face to the none lod texture support
  81310. if (generateNonLODTextures) {
  81311. var lodTexture = lodTextures[i];
  81312. if (lodTexture) {
  81313. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  81314. }
  81315. }
  81316. resolve();
  81317. }
  81318. };
  81319. image.onerror = function (error) {
  81320. reject(error);
  81321. };
  81322. });
  81323. promises.push(promise);
  81324. };
  81325. // All faces
  81326. for (var face = 0; face < 6; face++) {
  81327. _loop_4(face);
  81328. }
  81329. };
  81330. // All mipmaps
  81331. for (var i = 0; i < mipmapsCount; i++) {
  81332. _loop_3(i);
  81333. }
  81334. // Once all done, finishes the cleanup and return
  81335. return Promise.all(promises).then(function () {
  81336. // Relase temp RTT.
  81337. if (cubeRtt) {
  81338. engine._releaseFramebufferObjects(cubeRtt);
  81339. cubeRtt._swapAndDie(texture);
  81340. }
  81341. // Relase temp Post Process.
  81342. if (rgbdPostProcess) {
  81343. rgbdPostProcess.dispose();
  81344. }
  81345. // Flag internal texture as ready in case they are in use.
  81346. if (generateNonLODTextures) {
  81347. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  81348. texture._lodTextureHigh._texture.isReady = true;
  81349. }
  81350. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  81351. texture._lodTextureMid._texture.isReady = true;
  81352. }
  81353. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  81354. texture._lodTextureLow._texture.isReady = true;
  81355. }
  81356. }
  81357. });
  81358. };
  81359. /**
  81360. * Uploads spherical polynomials information to the texture.
  81361. * @param texture defines the texture we are trying to upload the information to
  81362. * @param arrayBuffer defines the array buffer holding the data
  81363. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  81364. */
  81365. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  81366. if (info.version !== 1) {
  81367. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  81368. }
  81369. var irradianceInfo = info.irradiance;
  81370. if (!irradianceInfo) {
  81371. return;
  81372. }
  81373. //harmonics now represent radiance
  81374. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  81375. if (irradianceInfo.polynomials) {
  81376. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  81377. }
  81378. else {
  81379. // convert From SH to SP.
  81380. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  81381. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  81382. }
  81383. };
  81384. /**
  81385. * Upload spherical polynomial coefficients to the texture
  81386. * @param polynmials Spherical polynmial coefficients (9)
  81387. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81388. */
  81389. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  81390. outPolynomialCoefficents.x.x = polynmials.x[0];
  81391. outPolynomialCoefficents.x.y = polynmials.x[1];
  81392. outPolynomialCoefficents.x.z = polynmials.x[2];
  81393. outPolynomialCoefficents.y.x = polynmials.y[0];
  81394. outPolynomialCoefficents.y.y = polynmials.y[1];
  81395. outPolynomialCoefficents.y.z = polynmials.y[2];
  81396. outPolynomialCoefficents.z.x = polynmials.z[0];
  81397. outPolynomialCoefficents.z.y = polynmials.z[1];
  81398. outPolynomialCoefficents.z.z = polynmials.z[2];
  81399. //xx
  81400. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  81401. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  81402. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  81403. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  81404. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  81405. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  81406. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  81407. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  81408. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  81409. //yz
  81410. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  81411. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  81412. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  81413. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  81414. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  81415. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  81416. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  81417. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  81418. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  81419. };
  81420. /**
  81421. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81422. * L = (1/pi) * E * rho
  81423. *
  81424. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81425. * @param harmonics Spherical harmonic coefficients (9)
  81426. */
  81427. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  81428. var scaleFactor = 1 / Math.PI;
  81429. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81430. // (The pixel shader must apply albedo after texture fetches, etc).
  81431. harmonics.l00[0] *= scaleFactor;
  81432. harmonics.l00[1] *= scaleFactor;
  81433. harmonics.l00[2] *= scaleFactor;
  81434. harmonics.l1_1[0] *= scaleFactor;
  81435. harmonics.l1_1[1] *= scaleFactor;
  81436. harmonics.l1_1[2] *= scaleFactor;
  81437. harmonics.l10[0] *= scaleFactor;
  81438. harmonics.l10[1] *= scaleFactor;
  81439. harmonics.l10[2] *= scaleFactor;
  81440. harmonics.l11[0] *= scaleFactor;
  81441. harmonics.l11[1] *= scaleFactor;
  81442. harmonics.l11[2] *= scaleFactor;
  81443. harmonics.l2_2[0] *= scaleFactor;
  81444. harmonics.l2_2[1] *= scaleFactor;
  81445. harmonics.l2_2[2] *= scaleFactor;
  81446. harmonics.l2_1[0] *= scaleFactor;
  81447. harmonics.l2_1[1] *= scaleFactor;
  81448. harmonics.l2_1[2] *= scaleFactor;
  81449. harmonics.l20[0] *= scaleFactor;
  81450. harmonics.l20[1] *= scaleFactor;
  81451. harmonics.l20[2] *= scaleFactor;
  81452. harmonics.l21[0] *= scaleFactor;
  81453. harmonics.l21[1] *= scaleFactor;
  81454. harmonics.l21[2] *= scaleFactor;
  81455. harmonics.l22[0] *= scaleFactor;
  81456. harmonics.l22[1] *= scaleFactor;
  81457. harmonics.l22[2] *= scaleFactor;
  81458. };
  81459. /**
  81460. * Convert spherical harmonics to spherical polynomial coefficients
  81461. * @param harmonics Spherical harmonic coefficients (9)
  81462. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  81463. */
  81464. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  81465. var rPi = 1 / Math.PI;
  81466. //x
  81467. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  81468. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  81469. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  81470. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  81471. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  81472. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  81473. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  81474. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  81475. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  81476. //xx
  81477. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  81478. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  81479. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  81480. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  81481. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  81482. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  81483. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  81484. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  81485. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  81486. //yz
  81487. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  81488. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  81489. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  81490. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  81491. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  81492. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  81493. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  81494. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  81495. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  81496. };
  81497. /**
  81498. * Magic number identifying the env file.
  81499. */
  81500. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  81501. return EnvironmentTextureTools;
  81502. }());
  81503. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  81504. })(BABYLON || (BABYLON = {}));
  81505. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  81506. var BABYLON;
  81507. (function (BABYLON) {
  81508. /**
  81509. * This represents a texture coming from an HDR input.
  81510. *
  81511. * The only supported format is currently panorama picture stored in RGBE format.
  81512. * Example of such files can be found on HDRLib: http://hdrlib.com/
  81513. */
  81514. var HDRCubeTexture = /** @class */ (function (_super) {
  81515. __extends(HDRCubeTexture, _super);
  81516. /**
  81517. * Instantiates an HDRTexture from the following parameters.
  81518. *
  81519. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  81520. * @param scene The scene the texture will be used in
  81521. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  81522. * @param noMipmap Forces to not generate the mipmap if true
  81523. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  81524. * @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)
  81525. * @param reserved Reserved flag for internal use.
  81526. */
  81527. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  81528. if (noMipmap === void 0) { noMipmap = false; }
  81529. if (generateHarmonics === void 0) { generateHarmonics = true; }
  81530. if (gammaSpace === void 0) { gammaSpace = false; }
  81531. if (reserved === void 0) { reserved = false; }
  81532. if (onLoad === void 0) { onLoad = null; }
  81533. if (onError === void 0) { onError = null; }
  81534. var _this = _super.call(this, scene) || this;
  81535. _this._generateHarmonics = true;
  81536. _this._onLoad = null;
  81537. _this._onError = null;
  81538. /**
  81539. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  81540. */
  81541. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  81542. _this._isBlocking = true;
  81543. _this._rotationY = 0;
  81544. /**
  81545. * Gets or sets the center of the bounding box associated with the cube texture
  81546. * It must define where the camera used to render the texture was set
  81547. */
  81548. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  81549. if (!url) {
  81550. return _this;
  81551. }
  81552. _this.name = url;
  81553. _this.url = url;
  81554. _this.hasAlpha = false;
  81555. _this.isCube = true;
  81556. _this._textureMatrix = BABYLON.Matrix.Identity();
  81557. _this._onLoad = onLoad;
  81558. _this._onError = onError;
  81559. _this.gammaSpace = gammaSpace;
  81560. _this._noMipmap = noMipmap;
  81561. _this._size = size;
  81562. _this._texture = _this._getFromCache(url, _this._noMipmap);
  81563. if (!_this._texture) {
  81564. if (!scene.useDelayedTextureLoading) {
  81565. _this.loadTexture();
  81566. }
  81567. else {
  81568. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  81569. }
  81570. }
  81571. return _this;
  81572. }
  81573. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  81574. /**
  81575. * Gets wether or not the texture is blocking during loading.
  81576. */
  81577. get: function () {
  81578. return this._isBlocking;
  81579. },
  81580. /**
  81581. * Sets wether or not the texture is blocking during loading.
  81582. */
  81583. set: function (value) {
  81584. this._isBlocking = value;
  81585. },
  81586. enumerable: true,
  81587. configurable: true
  81588. });
  81589. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81590. /**
  81591. * Gets texture matrix rotation angle around Y axis radians.
  81592. */
  81593. get: function () {
  81594. return this._rotationY;
  81595. },
  81596. /**
  81597. * Sets texture matrix rotation angle around Y axis in radians.
  81598. */
  81599. set: function (value) {
  81600. this._rotationY = value;
  81601. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81602. },
  81603. enumerable: true,
  81604. configurable: true
  81605. });
  81606. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81607. get: function () {
  81608. return this._boundingBoxSize;
  81609. },
  81610. /**
  81611. * Gets or sets the size of the bounding box associated with the cube texture
  81612. * When defined, the cubemap will switch to local mode
  81613. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81614. * @example https://www.babylonjs-playground.com/#RNASML
  81615. */
  81616. set: function (value) {
  81617. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81618. return;
  81619. }
  81620. this._boundingBoxSize = value;
  81621. var scene = this.getScene();
  81622. if (scene) {
  81623. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81624. }
  81625. },
  81626. enumerable: true,
  81627. configurable: true
  81628. });
  81629. /**
  81630. * Occurs when the file is raw .hdr file.
  81631. */
  81632. HDRCubeTexture.prototype.loadTexture = function () {
  81633. var _this = this;
  81634. var callback = function (buffer) {
  81635. var scene = _this.getScene();
  81636. if (!scene) {
  81637. return null;
  81638. }
  81639. // Extract the raw linear data.
  81640. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81641. // Generate harmonics if needed.
  81642. if (_this._generateHarmonics) {
  81643. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81644. _this.sphericalPolynomial = sphericalPolynomial;
  81645. }
  81646. var results = [];
  81647. var byteArray = null;
  81648. // Push each faces.
  81649. for (var j = 0; j < 6; j++) {
  81650. // Create uintarray fallback.
  81651. if (!scene.getEngine().getCaps().textureFloat) {
  81652. // 3 channels of 1 bytes per pixel in bytes.
  81653. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81654. byteArray = new Uint8Array(byteBuffer);
  81655. }
  81656. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81657. // If special cases.
  81658. if (_this.gammaSpace || byteArray) {
  81659. for (var i = 0; i < _this._size * _this._size; i++) {
  81660. // Put in gamma space if requested.
  81661. if (_this.gammaSpace) {
  81662. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81663. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81664. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81665. }
  81666. // Convert to int texture for fallback.
  81667. if (byteArray) {
  81668. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81669. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81670. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81671. // May use luminance instead if the result is not accurate.
  81672. var max = Math.max(Math.max(r, g), b);
  81673. if (max > 255) {
  81674. var scale = 255 / max;
  81675. r *= scale;
  81676. g *= scale;
  81677. b *= scale;
  81678. }
  81679. byteArray[(i * 3) + 0] = r;
  81680. byteArray[(i * 3) + 1] = g;
  81681. byteArray[(i * 3) + 2] = b;
  81682. }
  81683. }
  81684. }
  81685. if (byteArray) {
  81686. results.push(byteArray);
  81687. }
  81688. else {
  81689. results.push(dataFace);
  81690. }
  81691. }
  81692. return results;
  81693. };
  81694. var scene = this.getScene();
  81695. if (scene) {
  81696. 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);
  81697. }
  81698. };
  81699. HDRCubeTexture.prototype.clone = function () {
  81700. var scene = this.getScene();
  81701. if (!scene) {
  81702. return this;
  81703. }
  81704. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81705. // Base texture
  81706. newTexture.level = this.level;
  81707. newTexture.wrapU = this.wrapU;
  81708. newTexture.wrapV = this.wrapV;
  81709. newTexture.coordinatesIndex = this.coordinatesIndex;
  81710. newTexture.coordinatesMode = this.coordinatesMode;
  81711. return newTexture;
  81712. };
  81713. // Methods
  81714. HDRCubeTexture.prototype.delayLoad = function () {
  81715. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81716. return;
  81717. }
  81718. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81719. this._texture = this._getFromCache(this.url, this._noMipmap);
  81720. if (!this._texture) {
  81721. this.loadTexture();
  81722. }
  81723. };
  81724. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81725. return this._textureMatrix;
  81726. };
  81727. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81728. this._textureMatrix = value;
  81729. };
  81730. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81731. var texture = null;
  81732. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81733. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81734. texture.name = parsedTexture.name;
  81735. texture.hasAlpha = parsedTexture.hasAlpha;
  81736. texture.level = parsedTexture.level;
  81737. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81738. texture.isBlocking = parsedTexture.isBlocking;
  81739. }
  81740. if (texture) {
  81741. if (parsedTexture.boundingBoxPosition) {
  81742. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81743. }
  81744. if (parsedTexture.boundingBoxSize) {
  81745. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81746. }
  81747. if (parsedTexture.rotationY) {
  81748. texture.rotationY = parsedTexture.rotationY;
  81749. }
  81750. }
  81751. return texture;
  81752. };
  81753. HDRCubeTexture.prototype.serialize = function () {
  81754. if (!this.name) {
  81755. return null;
  81756. }
  81757. var serializationObject = {};
  81758. serializationObject.name = this.name;
  81759. serializationObject.hasAlpha = this.hasAlpha;
  81760. serializationObject.isCube = true;
  81761. serializationObject.level = this.level;
  81762. serializationObject.size = this._size;
  81763. serializationObject.coordinatesMode = this.coordinatesMode;
  81764. serializationObject.useInGammaSpace = this.gammaSpace;
  81765. serializationObject.generateHarmonics = this._generateHarmonics;
  81766. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81767. serializationObject.noMipmap = this._noMipmap;
  81768. serializationObject.isBlocking = this._isBlocking;
  81769. serializationObject.rotationY = this._rotationY;
  81770. return serializationObject;
  81771. };
  81772. HDRCubeTexture._facesMapping = [
  81773. "right",
  81774. "left",
  81775. "up",
  81776. "down",
  81777. "front",
  81778. "back"
  81779. ];
  81780. return HDRCubeTexture;
  81781. }(BABYLON.BaseTexture));
  81782. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81783. })(BABYLON || (BABYLON = {}));
  81784. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81785. var BABYLON;
  81786. (function (BABYLON) {
  81787. var IndexedVector2 = /** @class */ (function (_super) {
  81788. __extends(IndexedVector2, _super);
  81789. function IndexedVector2(original, index) {
  81790. var _this = _super.call(this, original.x, original.y) || this;
  81791. _this.index = index;
  81792. return _this;
  81793. }
  81794. return IndexedVector2;
  81795. }(BABYLON.Vector2));
  81796. var PolygonPoints = /** @class */ (function () {
  81797. function PolygonPoints() {
  81798. this.elements = new Array();
  81799. }
  81800. PolygonPoints.prototype.add = function (originalPoints) {
  81801. var _this = this;
  81802. var result = new Array();
  81803. originalPoints.forEach(function (point) {
  81804. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81805. var newPoint = new IndexedVector2(point, _this.elements.length);
  81806. result.push(newPoint);
  81807. _this.elements.push(newPoint);
  81808. }
  81809. });
  81810. return result;
  81811. };
  81812. PolygonPoints.prototype.computeBounds = function () {
  81813. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81814. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81815. this.elements.forEach(function (point) {
  81816. // x
  81817. if (point.x < lmin.x) {
  81818. lmin.x = point.x;
  81819. }
  81820. else if (point.x > lmax.x) {
  81821. lmax.x = point.x;
  81822. }
  81823. // y
  81824. if (point.y < lmin.y) {
  81825. lmin.y = point.y;
  81826. }
  81827. else if (point.y > lmax.y) {
  81828. lmax.y = point.y;
  81829. }
  81830. });
  81831. return {
  81832. min: lmin,
  81833. max: lmax,
  81834. width: lmax.x - lmin.x,
  81835. height: lmax.y - lmin.y
  81836. };
  81837. };
  81838. return PolygonPoints;
  81839. }());
  81840. var Polygon = /** @class */ (function () {
  81841. function Polygon() {
  81842. }
  81843. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81844. return [
  81845. new BABYLON.Vector2(xmin, ymin),
  81846. new BABYLON.Vector2(xmax, ymin),
  81847. new BABYLON.Vector2(xmax, ymax),
  81848. new BABYLON.Vector2(xmin, ymax)
  81849. ];
  81850. };
  81851. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81852. if (cx === void 0) { cx = 0; }
  81853. if (cy === void 0) { cy = 0; }
  81854. if (numberOfSides === void 0) { numberOfSides = 32; }
  81855. var result = new Array();
  81856. var angle = 0;
  81857. var increment = (Math.PI * 2) / numberOfSides;
  81858. for (var i = 0; i < numberOfSides; i++) {
  81859. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81860. angle -= increment;
  81861. }
  81862. return result;
  81863. };
  81864. Polygon.Parse = function (input) {
  81865. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81866. var i, result = [];
  81867. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81868. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81869. }
  81870. return result;
  81871. };
  81872. Polygon.StartingAt = function (x, y) {
  81873. return BABYLON.Path2.StartingAt(x, y);
  81874. };
  81875. return Polygon;
  81876. }());
  81877. BABYLON.Polygon = Polygon;
  81878. var PolygonMeshBuilder = /** @class */ (function () {
  81879. function PolygonMeshBuilder(name, contours, scene) {
  81880. this._points = new PolygonPoints();
  81881. this._outlinepoints = new PolygonPoints();
  81882. this._holes = new Array();
  81883. this._epoints = new Array();
  81884. this._eholes = new Array();
  81885. this._name = name;
  81886. this._scene = scene;
  81887. var points;
  81888. if (contours instanceof BABYLON.Path2) {
  81889. points = contours.getPoints();
  81890. }
  81891. else {
  81892. points = contours;
  81893. }
  81894. this._addToepoint(points);
  81895. this._points.add(points);
  81896. this._outlinepoints.add(points);
  81897. if (typeof earcut === 'undefined') {
  81898. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81899. }
  81900. }
  81901. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81902. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81903. var p = points_1[_i];
  81904. this._epoints.push(p.x, p.y);
  81905. }
  81906. };
  81907. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81908. this._points.add(hole);
  81909. var holepoints = new PolygonPoints();
  81910. holepoints.add(hole);
  81911. this._holes.push(holepoints);
  81912. this._eholes.push(this._epoints.length / 2);
  81913. this._addToepoint(hole);
  81914. return this;
  81915. };
  81916. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81917. var _this = this;
  81918. if (updatable === void 0) { updatable = false; }
  81919. if (depth === void 0) { depth = 0; }
  81920. var result = new BABYLON.Mesh(this._name, this._scene);
  81921. var normals = new Array();
  81922. var positions = new Array();
  81923. var uvs = new Array();
  81924. var bounds = this._points.computeBounds();
  81925. this._points.elements.forEach(function (p) {
  81926. normals.push(0, 1.0, 0);
  81927. positions.push(p.x, 0, p.y);
  81928. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81929. });
  81930. var indices = new Array();
  81931. var res = earcut(this._epoints, this._eholes, 2);
  81932. for (var i = 0; i < res.length; i++) {
  81933. indices.push(res[i]);
  81934. }
  81935. if (depth > 0) {
  81936. var positionscount = (positions.length / 3); //get the current pointcount
  81937. this._points.elements.forEach(function (p) {
  81938. normals.push(0, -1.0, 0);
  81939. positions.push(p.x, -depth, p.y);
  81940. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81941. });
  81942. var totalCount = indices.length;
  81943. for (var i = 0; i < totalCount; i += 3) {
  81944. var i0 = indices[i + 0];
  81945. var i1 = indices[i + 1];
  81946. var i2 = indices[i + 2];
  81947. indices.push(i2 + positionscount);
  81948. indices.push(i1 + positionscount);
  81949. indices.push(i0 + positionscount);
  81950. }
  81951. //Add the sides
  81952. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81953. this._holes.forEach(function (hole) {
  81954. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81955. });
  81956. }
  81957. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81958. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81959. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81960. result.setIndices(indices);
  81961. return result;
  81962. };
  81963. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81964. var StartIndex = positions.length / 3;
  81965. var ulength = 0;
  81966. for (var i = 0; i < points.elements.length; i++) {
  81967. var p = points.elements[i];
  81968. var p1;
  81969. if ((i + 1) > points.elements.length - 1) {
  81970. p1 = points.elements[0];
  81971. }
  81972. else {
  81973. p1 = points.elements[i + 1];
  81974. }
  81975. positions.push(p.x, 0, p.y);
  81976. positions.push(p.x, -depth, p.y);
  81977. positions.push(p1.x, 0, p1.y);
  81978. positions.push(p1.x, -depth, p1.y);
  81979. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81980. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81981. var v3 = v2.subtract(v1);
  81982. var v4 = new BABYLON.Vector3(0, 1, 0);
  81983. var vn = BABYLON.Vector3.Cross(v3, v4);
  81984. vn = vn.normalize();
  81985. uvs.push(ulength / bounds.width, 0);
  81986. uvs.push(ulength / bounds.width, 1);
  81987. ulength += v3.length();
  81988. uvs.push((ulength / bounds.width), 0);
  81989. uvs.push((ulength / bounds.width), 1);
  81990. if (!flip) {
  81991. normals.push(-vn.x, -vn.y, -vn.z);
  81992. normals.push(-vn.x, -vn.y, -vn.z);
  81993. normals.push(-vn.x, -vn.y, -vn.z);
  81994. normals.push(-vn.x, -vn.y, -vn.z);
  81995. indices.push(StartIndex);
  81996. indices.push(StartIndex + 1);
  81997. indices.push(StartIndex + 2);
  81998. indices.push(StartIndex + 1);
  81999. indices.push(StartIndex + 3);
  82000. indices.push(StartIndex + 2);
  82001. }
  82002. else {
  82003. normals.push(vn.x, vn.y, vn.z);
  82004. normals.push(vn.x, vn.y, vn.z);
  82005. normals.push(vn.x, vn.y, vn.z);
  82006. normals.push(vn.x, vn.y, vn.z);
  82007. indices.push(StartIndex);
  82008. indices.push(StartIndex + 2);
  82009. indices.push(StartIndex + 1);
  82010. indices.push(StartIndex + 1);
  82011. indices.push(StartIndex + 2);
  82012. indices.push(StartIndex + 3);
  82013. }
  82014. StartIndex += 4;
  82015. }
  82016. ;
  82017. };
  82018. return PolygonMeshBuilder;
  82019. }());
  82020. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82021. })(BABYLON || (BABYLON = {}));
  82022. //# sourceMappingURL=babylon.polygonMesh.js.map
  82023. var BABYLON;
  82024. (function (BABYLON) {
  82025. // Unique ID when we import meshes from Babylon to CSG
  82026. var currentCSGMeshId = 0;
  82027. // # class Vertex
  82028. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82029. // one to provide additional features like texture coordinates and vertex
  82030. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82031. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82032. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82033. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82034. // is not used anywhere else.
  82035. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82036. var Vertex = /** @class */ (function () {
  82037. function Vertex(pos, normal, uv) {
  82038. this.pos = pos;
  82039. this.normal = normal;
  82040. this.uv = uv;
  82041. }
  82042. Vertex.prototype.clone = function () {
  82043. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82044. };
  82045. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82046. // orientation of a polygon is flipped.
  82047. Vertex.prototype.flip = function () {
  82048. this.normal = this.normal.scale(-1);
  82049. };
  82050. // Create a new vertex between this vertex and `other` by linearly
  82051. // interpolating all properties using a parameter of `t`. Subclasses should
  82052. // override this to interpolate additional properties.
  82053. Vertex.prototype.interpolate = function (other, t) {
  82054. 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));
  82055. };
  82056. return Vertex;
  82057. }());
  82058. // # class Plane
  82059. // Represents a plane in 3D space.
  82060. var Plane = /** @class */ (function () {
  82061. function Plane(normal, w) {
  82062. this.normal = normal;
  82063. this.w = w;
  82064. }
  82065. Plane.FromPoints = function (a, b, c) {
  82066. var v0 = c.subtract(a);
  82067. var v1 = b.subtract(a);
  82068. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82069. return null;
  82070. }
  82071. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82072. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82073. };
  82074. Plane.prototype.clone = function () {
  82075. return new Plane(this.normal.clone(), this.w);
  82076. };
  82077. Plane.prototype.flip = function () {
  82078. this.normal.scaleInPlace(-1);
  82079. this.w = -this.w;
  82080. };
  82081. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82082. // fragments in the appropriate lists. Coplanar polygons go into either
  82083. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82084. // respect to this plane. Polygons in front or in back of this plane go into
  82085. // either `front` or `back`.
  82086. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82087. var COPLANAR = 0;
  82088. var FRONT = 1;
  82089. var BACK = 2;
  82090. var SPANNING = 3;
  82091. // Classify each point as well as the entire polygon into one of the above
  82092. // four classes.
  82093. var polygonType = 0;
  82094. var types = [];
  82095. var i;
  82096. var t;
  82097. for (i = 0; i < polygon.vertices.length; i++) {
  82098. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82099. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82100. polygonType |= type;
  82101. types.push(type);
  82102. }
  82103. // Put the polygon in the correct list, splitting it when necessary.
  82104. switch (polygonType) {
  82105. case COPLANAR:
  82106. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82107. break;
  82108. case FRONT:
  82109. front.push(polygon);
  82110. break;
  82111. case BACK:
  82112. back.push(polygon);
  82113. break;
  82114. case SPANNING:
  82115. var f = [], b = [];
  82116. for (i = 0; i < polygon.vertices.length; i++) {
  82117. var j = (i + 1) % polygon.vertices.length;
  82118. var ti = types[i], tj = types[j];
  82119. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82120. if (ti !== BACK)
  82121. f.push(vi);
  82122. if (ti !== FRONT)
  82123. b.push(ti !== BACK ? vi.clone() : vi);
  82124. if ((ti | tj) === SPANNING) {
  82125. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82126. var v = vi.interpolate(vj, t);
  82127. f.push(v);
  82128. b.push(v.clone());
  82129. }
  82130. }
  82131. var poly;
  82132. if (f.length >= 3) {
  82133. poly = new Polygon(f, polygon.shared);
  82134. if (poly.plane)
  82135. front.push(poly);
  82136. }
  82137. if (b.length >= 3) {
  82138. poly = new Polygon(b, polygon.shared);
  82139. if (poly.plane)
  82140. back.push(poly);
  82141. }
  82142. break;
  82143. }
  82144. };
  82145. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  82146. // point is on the plane.
  82147. Plane.EPSILON = 1e-5;
  82148. return Plane;
  82149. }());
  82150. // # class Polygon
  82151. // Represents a convex polygon. The vertices used to initialize a polygon must
  82152. // be coplanar and form a convex loop.
  82153. //
  82154. // Each convex polygon has a `shared` property, which is shared between all
  82155. // polygons that are clones of each other or were split from the same polygon.
  82156. // This can be used to define per-polygon properties (such as surface color).
  82157. var Polygon = /** @class */ (function () {
  82158. function Polygon(vertices, shared) {
  82159. this.vertices = vertices;
  82160. this.shared = shared;
  82161. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  82162. }
  82163. Polygon.prototype.clone = function () {
  82164. var vertices = this.vertices.map(function (v) { return v.clone(); });
  82165. return new Polygon(vertices, this.shared);
  82166. };
  82167. Polygon.prototype.flip = function () {
  82168. this.vertices.reverse().map(function (v) { v.flip(); });
  82169. this.plane.flip();
  82170. };
  82171. return Polygon;
  82172. }());
  82173. // # class Node
  82174. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  82175. // by picking a polygon to split along. That polygon (and all other coplanar
  82176. // polygons) are added directly to that node and the other polygons are added to
  82177. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  82178. // no distinction between internal and leaf nodes.
  82179. var Node = /** @class */ (function () {
  82180. function Node(polygons) {
  82181. this.plane = null;
  82182. this.front = null;
  82183. this.back = null;
  82184. this.polygons = new Array();
  82185. if (polygons) {
  82186. this.build(polygons);
  82187. }
  82188. }
  82189. Node.prototype.clone = function () {
  82190. var node = new Node();
  82191. node.plane = this.plane && this.plane.clone();
  82192. node.front = this.front && this.front.clone();
  82193. node.back = this.back && this.back.clone();
  82194. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  82195. return node;
  82196. };
  82197. // Convert solid space to empty space and empty space to solid space.
  82198. Node.prototype.invert = function () {
  82199. for (var i = 0; i < this.polygons.length; i++) {
  82200. this.polygons[i].flip();
  82201. }
  82202. if (this.plane) {
  82203. this.plane.flip();
  82204. }
  82205. if (this.front) {
  82206. this.front.invert();
  82207. }
  82208. if (this.back) {
  82209. this.back.invert();
  82210. }
  82211. var temp = this.front;
  82212. this.front = this.back;
  82213. this.back = temp;
  82214. };
  82215. // Recursively remove all polygons in `polygons` that are inside this BSP
  82216. // tree.
  82217. Node.prototype.clipPolygons = function (polygons) {
  82218. if (!this.plane)
  82219. return polygons.slice();
  82220. var front = new Array(), back = new Array();
  82221. for (var i = 0; i < polygons.length; i++) {
  82222. this.plane.splitPolygon(polygons[i], front, back, front, back);
  82223. }
  82224. if (this.front) {
  82225. front = this.front.clipPolygons(front);
  82226. }
  82227. if (this.back) {
  82228. back = this.back.clipPolygons(back);
  82229. }
  82230. else {
  82231. back = [];
  82232. }
  82233. return front.concat(back);
  82234. };
  82235. // Remove all polygons in this BSP tree that are inside the other BSP tree
  82236. // `bsp`.
  82237. Node.prototype.clipTo = function (bsp) {
  82238. this.polygons = bsp.clipPolygons(this.polygons);
  82239. if (this.front)
  82240. this.front.clipTo(bsp);
  82241. if (this.back)
  82242. this.back.clipTo(bsp);
  82243. };
  82244. // Return a list of all polygons in this BSP tree.
  82245. Node.prototype.allPolygons = function () {
  82246. var polygons = this.polygons.slice();
  82247. if (this.front)
  82248. polygons = polygons.concat(this.front.allPolygons());
  82249. if (this.back)
  82250. polygons = polygons.concat(this.back.allPolygons());
  82251. return polygons;
  82252. };
  82253. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  82254. // new polygons are filtered down to the bottom of the tree and become new
  82255. // nodes there. Each set of polygons is partitioned using the first polygon
  82256. // (no heuristic is used to pick a good split).
  82257. Node.prototype.build = function (polygons) {
  82258. if (!polygons.length)
  82259. return;
  82260. if (!this.plane)
  82261. this.plane = polygons[0].plane.clone();
  82262. var front = new Array(), back = new Array();
  82263. for (var i = 0; i < polygons.length; i++) {
  82264. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  82265. }
  82266. if (front.length) {
  82267. if (!this.front)
  82268. this.front = new Node();
  82269. this.front.build(front);
  82270. }
  82271. if (back.length) {
  82272. if (!this.back)
  82273. this.back = new Node();
  82274. this.back.build(back);
  82275. }
  82276. };
  82277. return Node;
  82278. }());
  82279. var CSG = /** @class */ (function () {
  82280. function CSG() {
  82281. this.polygons = new Array();
  82282. }
  82283. // Convert BABYLON.Mesh to BABYLON.CSG
  82284. CSG.FromMesh = function (mesh) {
  82285. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  82286. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  82287. if (mesh instanceof BABYLON.Mesh) {
  82288. mesh.computeWorldMatrix(true);
  82289. matrix = mesh.getWorldMatrix();
  82290. meshPosition = mesh.position.clone();
  82291. meshRotation = mesh.rotation.clone();
  82292. if (mesh.rotationQuaternion) {
  82293. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  82294. }
  82295. meshScaling = mesh.scaling.clone();
  82296. }
  82297. else {
  82298. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  82299. }
  82300. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82301. var subMeshes = mesh.subMeshes;
  82302. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  82303. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  82304. vertices = [];
  82305. for (var j = 0; j < 3; j++) {
  82306. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  82307. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  82308. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  82309. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  82310. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  82311. vertex = new Vertex(position, normal, uv);
  82312. vertices.push(vertex);
  82313. }
  82314. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  82315. // To handle the case of degenerated triangle
  82316. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  82317. if (polygon.plane)
  82318. polygons.push(polygon);
  82319. }
  82320. }
  82321. var csg = CSG.FromPolygons(polygons);
  82322. csg.matrix = matrix;
  82323. csg.position = meshPosition;
  82324. csg.rotation = meshRotation;
  82325. csg.scaling = meshScaling;
  82326. csg.rotationQuaternion = meshRotationQuaternion;
  82327. currentCSGMeshId++;
  82328. return csg;
  82329. };
  82330. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  82331. CSG.FromPolygons = function (polygons) {
  82332. var csg = new CSG();
  82333. csg.polygons = polygons;
  82334. return csg;
  82335. };
  82336. CSG.prototype.clone = function () {
  82337. var csg = new CSG();
  82338. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  82339. csg.copyTransformAttributes(this);
  82340. return csg;
  82341. };
  82342. CSG.prototype.union = function (csg) {
  82343. var a = new Node(this.clone().polygons);
  82344. var b = new Node(csg.clone().polygons);
  82345. a.clipTo(b);
  82346. b.clipTo(a);
  82347. b.invert();
  82348. b.clipTo(a);
  82349. b.invert();
  82350. a.build(b.allPolygons());
  82351. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82352. };
  82353. CSG.prototype.unionInPlace = function (csg) {
  82354. var a = new Node(this.polygons);
  82355. var b = new Node(csg.polygons);
  82356. a.clipTo(b);
  82357. b.clipTo(a);
  82358. b.invert();
  82359. b.clipTo(a);
  82360. b.invert();
  82361. a.build(b.allPolygons());
  82362. this.polygons = a.allPolygons();
  82363. };
  82364. CSG.prototype.subtract = function (csg) {
  82365. var a = new Node(this.clone().polygons);
  82366. var b = new Node(csg.clone().polygons);
  82367. a.invert();
  82368. a.clipTo(b);
  82369. b.clipTo(a);
  82370. b.invert();
  82371. b.clipTo(a);
  82372. b.invert();
  82373. a.build(b.allPolygons());
  82374. a.invert();
  82375. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82376. };
  82377. CSG.prototype.subtractInPlace = function (csg) {
  82378. var a = new Node(this.polygons);
  82379. var b = new Node(csg.polygons);
  82380. a.invert();
  82381. a.clipTo(b);
  82382. b.clipTo(a);
  82383. b.invert();
  82384. b.clipTo(a);
  82385. b.invert();
  82386. a.build(b.allPolygons());
  82387. a.invert();
  82388. this.polygons = a.allPolygons();
  82389. };
  82390. CSG.prototype.intersect = function (csg) {
  82391. var a = new Node(this.clone().polygons);
  82392. var b = new Node(csg.clone().polygons);
  82393. a.invert();
  82394. b.clipTo(a);
  82395. b.invert();
  82396. a.clipTo(b);
  82397. b.clipTo(a);
  82398. a.build(b.allPolygons());
  82399. a.invert();
  82400. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  82401. };
  82402. CSG.prototype.intersectInPlace = function (csg) {
  82403. var a = new Node(this.polygons);
  82404. var b = new Node(csg.polygons);
  82405. a.invert();
  82406. b.clipTo(a);
  82407. b.invert();
  82408. a.clipTo(b);
  82409. b.clipTo(a);
  82410. a.build(b.allPolygons());
  82411. a.invert();
  82412. this.polygons = a.allPolygons();
  82413. };
  82414. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  82415. // not modified.
  82416. CSG.prototype.inverse = function () {
  82417. var csg = this.clone();
  82418. csg.inverseInPlace();
  82419. return csg;
  82420. };
  82421. CSG.prototype.inverseInPlace = function () {
  82422. this.polygons.map(function (p) { p.flip(); });
  82423. };
  82424. // This is used to keep meshes transformations so they can be restored
  82425. // when we build back a Babylon Mesh
  82426. // NB : All CSG operations are performed in world coordinates
  82427. CSG.prototype.copyTransformAttributes = function (csg) {
  82428. this.matrix = csg.matrix;
  82429. this.position = csg.position;
  82430. this.rotation = csg.rotation;
  82431. this.scaling = csg.scaling;
  82432. this.rotationQuaternion = csg.rotationQuaternion;
  82433. return this;
  82434. };
  82435. // Build Raw mesh from CSG
  82436. // Coordinates here are in world space
  82437. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  82438. var matrix = this.matrix.clone();
  82439. matrix.invert();
  82440. 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;
  82441. if (keepSubMeshes) {
  82442. // Sort Polygons, since subMeshes are indices range
  82443. polygons.sort(function (a, b) {
  82444. if (a.shared.meshId === b.shared.meshId) {
  82445. return a.shared.subMeshId - b.shared.subMeshId;
  82446. }
  82447. else {
  82448. return a.shared.meshId - b.shared.meshId;
  82449. }
  82450. });
  82451. }
  82452. for (var i = 0, il = polygons.length; i < il; i++) {
  82453. polygon = polygons[i];
  82454. // Building SubMeshes
  82455. if (!subMesh_dict[polygon.shared.meshId]) {
  82456. subMesh_dict[polygon.shared.meshId] = {};
  82457. }
  82458. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  82459. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  82460. indexStart: +Infinity,
  82461. indexEnd: -Infinity,
  82462. materialIndex: polygon.shared.materialIndex
  82463. };
  82464. }
  82465. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  82466. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  82467. polygonIndices[0] = 0;
  82468. polygonIndices[1] = j - 1;
  82469. polygonIndices[2] = j;
  82470. for (var k = 0; k < 3; k++) {
  82471. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  82472. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  82473. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  82474. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  82475. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  82476. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  82477. // Check if 2 points can be merged
  82478. if (!(typeof vertex_idx !== 'undefined' &&
  82479. normals[vertex_idx * 3] === localNormal.x &&
  82480. normals[vertex_idx * 3 + 1] === localNormal.y &&
  82481. normals[vertex_idx * 3 + 2] === localNormal.z &&
  82482. uvs[vertex_idx * 2] === uv.x &&
  82483. uvs[vertex_idx * 2 + 1] === uv.y)) {
  82484. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  82485. uvs.push(uv.x, uv.y);
  82486. normals.push(normal.x, normal.y, normal.z);
  82487. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  82488. }
  82489. indices.push(vertex_idx);
  82490. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  82491. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  82492. currentIndex++;
  82493. }
  82494. }
  82495. }
  82496. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  82497. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  82498. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  82499. mesh.setIndices(indices, null);
  82500. if (keepSubMeshes) {
  82501. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  82502. var materialIndexOffset = 0, materialMaxIndex;
  82503. mesh.subMeshes = new Array();
  82504. for (var m in subMesh_dict) {
  82505. materialMaxIndex = -1;
  82506. for (var sm in subMesh_dict[m]) {
  82507. subMesh_obj = subMesh_dict[m][sm];
  82508. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  82509. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  82510. }
  82511. materialIndexOffset += ++materialMaxIndex;
  82512. }
  82513. }
  82514. return mesh;
  82515. };
  82516. // Build Mesh from CSG taking material and transforms into account
  82517. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  82518. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  82519. mesh.material = material;
  82520. mesh.position.copyFrom(this.position);
  82521. mesh.rotation.copyFrom(this.rotation);
  82522. if (this.rotationQuaternion) {
  82523. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  82524. }
  82525. mesh.scaling.copyFrom(this.scaling);
  82526. mesh.computeWorldMatrix(true);
  82527. return mesh;
  82528. };
  82529. return CSG;
  82530. }());
  82531. BABYLON.CSG = CSG;
  82532. })(BABYLON || (BABYLON = {}));
  82533. //# sourceMappingURL=babylon.csg.js.map
  82534. var BABYLON;
  82535. (function (BABYLON) {
  82536. var LensFlare = /** @class */ (function () {
  82537. function LensFlare(size, position, color, imgUrl, system) {
  82538. this.size = size;
  82539. this.position = position;
  82540. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  82541. this.color = color || new BABYLON.Color3(1, 1, 1);
  82542. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  82543. this._system = system;
  82544. system.lensFlares.push(this);
  82545. }
  82546. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  82547. return new LensFlare(size, position, color, imgUrl, system);
  82548. };
  82549. LensFlare.prototype.dispose = function () {
  82550. if (this.texture) {
  82551. this.texture.dispose();
  82552. }
  82553. // Remove from scene
  82554. var index = this._system.lensFlares.indexOf(this);
  82555. this._system.lensFlares.splice(index, 1);
  82556. };
  82557. ;
  82558. return LensFlare;
  82559. }());
  82560. BABYLON.LensFlare = LensFlare;
  82561. })(BABYLON || (BABYLON = {}));
  82562. //# sourceMappingURL=babylon.lensFlare.js.map
  82563. var BABYLON;
  82564. (function (BABYLON) {
  82565. var LensFlareSystem = /** @class */ (function () {
  82566. function LensFlareSystem(name, emitter, scene) {
  82567. this.name = name;
  82568. this.lensFlares = new Array();
  82569. this.borderLimit = 300;
  82570. this.viewportBorder = 0;
  82571. this.layerMask = 0x0FFFFFFF;
  82572. this._vertexBuffers = {};
  82573. this._isEnabled = true;
  82574. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82575. this._emitter = emitter;
  82576. this.id = name;
  82577. scene.lensFlareSystems.push(this);
  82578. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  82579. var engine = scene.getEngine();
  82580. // VBO
  82581. var vertices = [];
  82582. vertices.push(1, 1);
  82583. vertices.push(-1, 1);
  82584. vertices.push(-1, -1);
  82585. vertices.push(1, -1);
  82586. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82587. // Indices
  82588. var indices = [];
  82589. indices.push(0);
  82590. indices.push(1);
  82591. indices.push(2);
  82592. indices.push(0);
  82593. indices.push(2);
  82594. indices.push(3);
  82595. this._indexBuffer = engine.createIndexBuffer(indices);
  82596. // Effects
  82597. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82598. }
  82599. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82600. get: function () {
  82601. return this._isEnabled;
  82602. },
  82603. set: function (value) {
  82604. this._isEnabled = value;
  82605. },
  82606. enumerable: true,
  82607. configurable: true
  82608. });
  82609. LensFlareSystem.prototype.getScene = function () {
  82610. return this._scene;
  82611. };
  82612. LensFlareSystem.prototype.getEmitter = function () {
  82613. return this._emitter;
  82614. };
  82615. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82616. this._emitter = newEmitter;
  82617. };
  82618. LensFlareSystem.prototype.getEmitterPosition = function () {
  82619. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82620. };
  82621. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82622. var position = this.getEmitterPosition();
  82623. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82624. this._positionX = position.x;
  82625. this._positionY = position.y;
  82626. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82627. if (this.viewportBorder > 0) {
  82628. globalViewport.x -= this.viewportBorder;
  82629. globalViewport.y -= this.viewportBorder;
  82630. globalViewport.width += this.viewportBorder * 2;
  82631. globalViewport.height += this.viewportBorder * 2;
  82632. position.x += this.viewportBorder;
  82633. position.y += this.viewportBorder;
  82634. this._positionX += this.viewportBorder;
  82635. this._positionY += this.viewportBorder;
  82636. }
  82637. if (position.z > 0) {
  82638. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82639. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82640. return true;
  82641. }
  82642. return true;
  82643. }
  82644. return false;
  82645. };
  82646. LensFlareSystem.prototype._isVisible = function () {
  82647. if (!this._isEnabled || !this._scene.activeCamera) {
  82648. return false;
  82649. }
  82650. var emitterPosition = this.getEmitterPosition();
  82651. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82652. var distance = direction.length();
  82653. direction.normalize();
  82654. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82655. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82656. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82657. };
  82658. LensFlareSystem.prototype.render = function () {
  82659. if (!this._effect.isReady() || !this._scene.activeCamera)
  82660. return false;
  82661. var engine = this._scene.getEngine();
  82662. var viewport = this._scene.activeCamera.viewport;
  82663. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82664. // Position
  82665. if (!this.computeEffectivePosition(globalViewport)) {
  82666. return false;
  82667. }
  82668. // Visibility
  82669. if (!this._isVisible()) {
  82670. return false;
  82671. }
  82672. // Intensity
  82673. var awayX;
  82674. var awayY;
  82675. if (this._positionX < this.borderLimit + globalViewport.x) {
  82676. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82677. }
  82678. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82679. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82680. }
  82681. else {
  82682. awayX = 0;
  82683. }
  82684. if (this._positionY < this.borderLimit + globalViewport.y) {
  82685. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82686. }
  82687. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82688. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82689. }
  82690. else {
  82691. awayY = 0;
  82692. }
  82693. var away = (awayX > awayY) ? awayX : awayY;
  82694. away -= this.viewportBorder;
  82695. if (away > this.borderLimit) {
  82696. away = this.borderLimit;
  82697. }
  82698. var intensity = 1.0 - (away / this.borderLimit);
  82699. if (intensity < 0) {
  82700. return false;
  82701. }
  82702. if (intensity > 1.0) {
  82703. intensity = 1.0;
  82704. }
  82705. if (this.viewportBorder > 0) {
  82706. globalViewport.x += this.viewportBorder;
  82707. globalViewport.y += this.viewportBorder;
  82708. globalViewport.width -= this.viewportBorder * 2;
  82709. globalViewport.height -= this.viewportBorder * 2;
  82710. this._positionX -= this.viewportBorder;
  82711. this._positionY -= this.viewportBorder;
  82712. }
  82713. // Position
  82714. var centerX = globalViewport.x + globalViewport.width / 2;
  82715. var centerY = globalViewport.y + globalViewport.height / 2;
  82716. var distX = centerX - this._positionX;
  82717. var distY = centerY - this._positionY;
  82718. // Effects
  82719. engine.enableEffect(this._effect);
  82720. engine.setState(false);
  82721. engine.setDepthBuffer(false);
  82722. // VBOs
  82723. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82724. // Flares
  82725. for (var index = 0; index < this.lensFlares.length; index++) {
  82726. var flare = this.lensFlares[index];
  82727. engine.setAlphaMode(flare.alphaMode);
  82728. var x = centerX - (distX * flare.position);
  82729. var y = centerY - (distY * flare.position);
  82730. var cw = flare.size;
  82731. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82732. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82733. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82734. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82735. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82736. // Texture
  82737. this._effect.setTexture("textureSampler", flare.texture);
  82738. // Color
  82739. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82740. // Draw order
  82741. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82742. }
  82743. engine.setDepthBuffer(true);
  82744. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82745. return true;
  82746. };
  82747. LensFlareSystem.prototype.dispose = function () {
  82748. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82749. if (vertexBuffer) {
  82750. vertexBuffer.dispose();
  82751. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82752. }
  82753. if (this._indexBuffer) {
  82754. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82755. this._indexBuffer = null;
  82756. }
  82757. while (this.lensFlares.length) {
  82758. this.lensFlares[0].dispose();
  82759. }
  82760. // Remove from scene
  82761. var index = this._scene.lensFlareSystems.indexOf(this);
  82762. this._scene.lensFlareSystems.splice(index, 1);
  82763. };
  82764. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82765. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82766. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82767. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82768. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82769. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82770. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82771. var parsedFlare = parsedLensFlareSystem.flares[index];
  82772. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82773. }
  82774. return lensFlareSystem;
  82775. };
  82776. LensFlareSystem.prototype.serialize = function () {
  82777. var serializationObject = {};
  82778. serializationObject.id = this.id;
  82779. serializationObject.name = this.name;
  82780. serializationObject.emitterId = this.getEmitter().id;
  82781. serializationObject.borderLimit = this.borderLimit;
  82782. serializationObject.flares = [];
  82783. for (var index = 0; index < this.lensFlares.length; index++) {
  82784. var flare = this.lensFlares[index];
  82785. serializationObject.flares.push({
  82786. size: flare.size,
  82787. position: flare.position,
  82788. color: flare.color.asArray(),
  82789. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82790. });
  82791. }
  82792. return serializationObject;
  82793. };
  82794. return LensFlareSystem;
  82795. }());
  82796. BABYLON.LensFlareSystem = LensFlareSystem;
  82797. })(BABYLON || (BABYLON = {}));
  82798. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82799. var BABYLON;
  82800. (function (BABYLON) {
  82801. /**
  82802. * This is a holder class for the physics joint created by the physics plugin.
  82803. * It holds a set of functions to control the underlying joint.
  82804. */
  82805. var PhysicsJoint = /** @class */ (function () {
  82806. function PhysicsJoint(type, jointData) {
  82807. this.type = type;
  82808. this.jointData = jointData;
  82809. jointData.nativeParams = jointData.nativeParams || {};
  82810. }
  82811. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82812. get: function () {
  82813. return this._physicsJoint;
  82814. },
  82815. set: function (newJoint) {
  82816. if (this._physicsJoint) {
  82817. //remove from the wolrd
  82818. }
  82819. this._physicsJoint = newJoint;
  82820. },
  82821. enumerable: true,
  82822. configurable: true
  82823. });
  82824. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82825. set: function (physicsPlugin) {
  82826. this._physicsPlugin = physicsPlugin;
  82827. },
  82828. enumerable: true,
  82829. configurable: true
  82830. });
  82831. /**
  82832. * Execute a function that is physics-plugin specific.
  82833. * @param {Function} func the function that will be executed.
  82834. * It accepts two parameters: the physics world and the physics joint.
  82835. */
  82836. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82837. func(this._physicsPlugin.world, this._physicsJoint);
  82838. };
  82839. //TODO check if the native joints are the same
  82840. //Joint Types
  82841. PhysicsJoint.DistanceJoint = 0;
  82842. PhysicsJoint.HingeJoint = 1;
  82843. PhysicsJoint.BallAndSocketJoint = 2;
  82844. PhysicsJoint.WheelJoint = 3;
  82845. PhysicsJoint.SliderJoint = 4;
  82846. //OIMO
  82847. PhysicsJoint.PrismaticJoint = 5;
  82848. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82849. PhysicsJoint.UniversalJoint = 6;
  82850. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82851. //Cannon
  82852. //Similar to a Ball-Joint. Different in params
  82853. PhysicsJoint.PointToPointJoint = 8;
  82854. //Cannon only at the moment
  82855. PhysicsJoint.SpringJoint = 9;
  82856. PhysicsJoint.LockJoint = 10;
  82857. return PhysicsJoint;
  82858. }());
  82859. BABYLON.PhysicsJoint = PhysicsJoint;
  82860. /**
  82861. * A class representing a physics distance joint.
  82862. */
  82863. var DistanceJoint = /** @class */ (function (_super) {
  82864. __extends(DistanceJoint, _super);
  82865. function DistanceJoint(jointData) {
  82866. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82867. }
  82868. /**
  82869. * Update the predefined distance.
  82870. */
  82871. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82872. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82873. };
  82874. return DistanceJoint;
  82875. }(PhysicsJoint));
  82876. BABYLON.DistanceJoint = DistanceJoint;
  82877. var MotorEnabledJoint = /** @class */ (function (_super) {
  82878. __extends(MotorEnabledJoint, _super);
  82879. function MotorEnabledJoint(type, jointData) {
  82880. return _super.call(this, type, jointData) || this;
  82881. }
  82882. /**
  82883. * Set the motor values.
  82884. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82885. * @param {number} force the force to apply
  82886. * @param {number} maxForce max force for this motor.
  82887. */
  82888. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82889. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82890. };
  82891. /**
  82892. * Set the motor's limits.
  82893. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82894. */
  82895. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82896. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82897. };
  82898. return MotorEnabledJoint;
  82899. }(PhysicsJoint));
  82900. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82901. /**
  82902. * This class represents a single hinge physics joint
  82903. */
  82904. var HingeJoint = /** @class */ (function (_super) {
  82905. __extends(HingeJoint, _super);
  82906. function HingeJoint(jointData) {
  82907. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82908. }
  82909. /**
  82910. * Set the motor values.
  82911. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82912. * @param {number} force the force to apply
  82913. * @param {number} maxForce max force for this motor.
  82914. */
  82915. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82916. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82917. };
  82918. /**
  82919. * Set the motor's limits.
  82920. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82921. */
  82922. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82923. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82924. };
  82925. return HingeJoint;
  82926. }(MotorEnabledJoint));
  82927. BABYLON.HingeJoint = HingeJoint;
  82928. /**
  82929. * This class represents a dual hinge physics joint (same as wheel joint)
  82930. */
  82931. var Hinge2Joint = /** @class */ (function (_super) {
  82932. __extends(Hinge2Joint, _super);
  82933. function Hinge2Joint(jointData) {
  82934. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82935. }
  82936. /**
  82937. * Set the motor values.
  82938. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82939. * @param {number} force the force to apply
  82940. * @param {number} maxForce max force for this motor.
  82941. * @param {motorIndex} the motor's index, 0 or 1.
  82942. */
  82943. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82944. if (motorIndex === void 0) { motorIndex = 0; }
  82945. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82946. };
  82947. /**
  82948. * Set the motor limits.
  82949. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82950. * @param {number} upperLimit the upper limit
  82951. * @param {number} lowerLimit lower limit
  82952. * @param {motorIndex} the motor's index, 0 or 1.
  82953. */
  82954. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82955. if (motorIndex === void 0) { motorIndex = 0; }
  82956. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82957. };
  82958. return Hinge2Joint;
  82959. }(MotorEnabledJoint));
  82960. BABYLON.Hinge2Joint = Hinge2Joint;
  82961. })(BABYLON || (BABYLON = {}));
  82962. //# sourceMappingURL=babylon.physicsJoint.js.map
  82963. var BABYLON;
  82964. (function (BABYLON) {
  82965. var PhysicsImpostor = /** @class */ (function () {
  82966. function PhysicsImpostor(object, type, _options, _scene) {
  82967. if (_options === void 0) { _options = { mass: 0 }; }
  82968. var _this = this;
  82969. this.object = object;
  82970. this.type = type;
  82971. this._options = _options;
  82972. this._scene = _scene;
  82973. this._bodyUpdateRequired = false;
  82974. this._onBeforePhysicsStepCallbacks = new Array();
  82975. this._onAfterPhysicsStepCallbacks = new Array();
  82976. this._onPhysicsCollideCallbacks = [];
  82977. this._deltaPosition = BABYLON.Vector3.Zero();
  82978. this._isDisposed = false;
  82979. //temp variables for parent rotation calculations
  82980. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82981. this._tmpQuat = new BABYLON.Quaternion();
  82982. this._tmpQuat2 = new BABYLON.Quaternion();
  82983. /**
  82984. * this function is executed by the physics engine.
  82985. */
  82986. this.beforeStep = function () {
  82987. if (!_this._physicsEngine) {
  82988. return;
  82989. }
  82990. _this.object.translate(_this._deltaPosition, -1);
  82991. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82992. _this.object.computeWorldMatrix(false);
  82993. if (_this.object.parent && _this.object.rotationQuaternion) {
  82994. _this.getParentsRotation();
  82995. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82996. }
  82997. else {
  82998. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82999. }
  83000. if (!_this._options.disableBidirectionalTransformation) {
  83001. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83002. }
  83003. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83004. func(_this);
  83005. });
  83006. };
  83007. /**
  83008. * this function is executed by the physics engine.
  83009. */
  83010. this.afterStep = function () {
  83011. if (!_this._physicsEngine) {
  83012. return;
  83013. }
  83014. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83015. func(_this);
  83016. });
  83017. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83018. // object has now its world rotation. needs to be converted to local.
  83019. if (_this.object.parent && _this.object.rotationQuaternion) {
  83020. _this.getParentsRotation();
  83021. _this._tmpQuat.conjugateInPlace();
  83022. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83023. }
  83024. // take the position set and make it the absolute position of this object.
  83025. _this.object.setAbsolutePosition(_this.object.position);
  83026. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83027. _this.object.translate(_this._deltaPosition, 1);
  83028. };
  83029. /**
  83030. * Legacy collision detection event support
  83031. */
  83032. this.onCollideEvent = null;
  83033. //event and body object due to cannon's event-based architecture.
  83034. this.onCollide = function (e) {
  83035. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83036. return;
  83037. }
  83038. if (!_this._physicsEngine) {
  83039. return;
  83040. }
  83041. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83042. if (otherImpostor) {
  83043. // Legacy collision detection event support
  83044. if (_this.onCollideEvent) {
  83045. _this.onCollideEvent(_this, otherImpostor);
  83046. }
  83047. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83048. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83049. }).forEach(function (obj) {
  83050. obj.callback(_this, otherImpostor);
  83051. });
  83052. }
  83053. };
  83054. //sanity check!
  83055. if (!this.object) {
  83056. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83057. return;
  83058. }
  83059. //legacy support for old syntax.
  83060. if (!this._scene && object.getScene) {
  83061. this._scene = object.getScene();
  83062. }
  83063. if (!this._scene) {
  83064. return;
  83065. }
  83066. this._physicsEngine = this._scene.getPhysicsEngine();
  83067. if (!this._physicsEngine) {
  83068. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83069. }
  83070. else {
  83071. //set the object's quaternion, if not set
  83072. if (!this.object.rotationQuaternion) {
  83073. if (this.object.rotation) {
  83074. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83075. }
  83076. else {
  83077. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83078. }
  83079. }
  83080. //default options params
  83081. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83082. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83083. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83084. this._joints = [];
  83085. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83086. if (!this.object.parent || this._options.ignoreParent) {
  83087. this._init();
  83088. }
  83089. else if (this.object.parent.physicsImpostor) {
  83090. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83091. }
  83092. }
  83093. }
  83094. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83095. get: function () {
  83096. return this._isDisposed;
  83097. },
  83098. enumerable: true,
  83099. configurable: true
  83100. });
  83101. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83102. get: function () {
  83103. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83104. },
  83105. set: function (value) {
  83106. this.setMass(value);
  83107. },
  83108. enumerable: true,
  83109. configurable: true
  83110. });
  83111. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83112. get: function () {
  83113. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83114. },
  83115. set: function (value) {
  83116. if (!this._physicsEngine) {
  83117. return;
  83118. }
  83119. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83120. },
  83121. enumerable: true,
  83122. configurable: true
  83123. });
  83124. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83125. get: function () {
  83126. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83127. },
  83128. set: function (value) {
  83129. if (!this._physicsEngine) {
  83130. return;
  83131. }
  83132. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  83133. },
  83134. enumerable: true,
  83135. configurable: true
  83136. });
  83137. /**
  83138. * This function will completly initialize this impostor.
  83139. * It will create a new body - but only if this mesh has no parent.
  83140. * If it has, this impostor will not be used other than to define the impostor
  83141. * of the child mesh.
  83142. */
  83143. PhysicsImpostor.prototype._init = function () {
  83144. if (!this._physicsEngine) {
  83145. return;
  83146. }
  83147. this._physicsEngine.removeImpostor(this);
  83148. this.physicsBody = null;
  83149. this._parent = this._parent || this._getPhysicsParent();
  83150. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  83151. this._physicsEngine.addImpostor(this);
  83152. }
  83153. };
  83154. PhysicsImpostor.prototype._getPhysicsParent = function () {
  83155. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  83156. var parentMesh = this.object.parent;
  83157. return parentMesh.physicsImpostor;
  83158. }
  83159. return null;
  83160. };
  83161. /**
  83162. * Should a new body be generated.
  83163. */
  83164. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  83165. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  83166. };
  83167. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  83168. this.forceUpdate();
  83169. };
  83170. /**
  83171. * Force a regeneration of this or the parent's impostor's body.
  83172. * Use under cautious - This will remove all joints already implemented.
  83173. */
  83174. PhysicsImpostor.prototype.forceUpdate = function () {
  83175. this._init();
  83176. if (this.parent && !this._options.ignoreParent) {
  83177. this.parent.forceUpdate();
  83178. }
  83179. };
  83180. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  83181. /*public get mesh(): AbstractMesh {
  83182. return this._mesh;
  83183. }*/
  83184. /**
  83185. * Gets the body that holds this impostor. Either its own, or its parent.
  83186. */
  83187. get: function () {
  83188. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  83189. },
  83190. /**
  83191. * Set the physics body. Used mainly by the physics engine/plugin
  83192. */
  83193. set: function (physicsBody) {
  83194. if (this._physicsBody && this._physicsEngine) {
  83195. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  83196. }
  83197. this._physicsBody = physicsBody;
  83198. this.resetUpdateFlags();
  83199. },
  83200. enumerable: true,
  83201. configurable: true
  83202. });
  83203. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  83204. get: function () {
  83205. return !this._options.ignoreParent && this._parent ? this._parent : null;
  83206. },
  83207. set: function (value) {
  83208. this._parent = value;
  83209. },
  83210. enumerable: true,
  83211. configurable: true
  83212. });
  83213. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  83214. this._bodyUpdateRequired = false;
  83215. };
  83216. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  83217. if (this.object.getBoundingInfo) {
  83218. var q = this.object.rotationQuaternion;
  83219. //reset rotation
  83220. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  83221. //calculate the world matrix with no rotation
  83222. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83223. var boundingInfo = this.object.getBoundingInfo();
  83224. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  83225. //bring back the rotation
  83226. this.object.rotationQuaternion = q;
  83227. //calculate the world matrix with the new rotation
  83228. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  83229. return size;
  83230. }
  83231. else {
  83232. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  83233. }
  83234. };
  83235. PhysicsImpostor.prototype.getObjectCenter = function () {
  83236. if (this.object.getBoundingInfo) {
  83237. var boundingInfo = this.object.getBoundingInfo();
  83238. return boundingInfo.boundingBox.centerWorld;
  83239. }
  83240. else {
  83241. return this.object.position;
  83242. }
  83243. };
  83244. /**
  83245. * Get a specific parametes from the options parameter.
  83246. */
  83247. PhysicsImpostor.prototype.getParam = function (paramName) {
  83248. return this._options[paramName];
  83249. };
  83250. /**
  83251. * Sets a specific parameter in the options given to the physics plugin
  83252. */
  83253. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  83254. this._options[paramName] = value;
  83255. this._bodyUpdateRequired = true;
  83256. };
  83257. /**
  83258. * Specifically change the body's mass option. Won't recreate the physics body object
  83259. */
  83260. PhysicsImpostor.prototype.setMass = function (mass) {
  83261. if (this.getParam("mass") !== mass) {
  83262. this.setParam("mass", mass);
  83263. }
  83264. if (this._physicsEngine) {
  83265. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  83266. }
  83267. };
  83268. PhysicsImpostor.prototype.getLinearVelocity = function () {
  83269. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  83270. };
  83271. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  83272. if (this._physicsEngine) {
  83273. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  83274. }
  83275. };
  83276. PhysicsImpostor.prototype.getAngularVelocity = function () {
  83277. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  83278. };
  83279. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  83280. if (this._physicsEngine) {
  83281. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  83282. }
  83283. };
  83284. /**
  83285. * Execute a function with the physics plugin native code.
  83286. * Provide a function the will have two variables - the world object and the physics body object.
  83287. */
  83288. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  83289. if (this._physicsEngine) {
  83290. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  83291. }
  83292. };
  83293. /**
  83294. * Register a function that will be executed before the physics world is stepping forward.
  83295. */
  83296. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  83297. this._onBeforePhysicsStepCallbacks.push(func);
  83298. };
  83299. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  83300. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  83301. if (index > -1) {
  83302. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  83303. }
  83304. else {
  83305. BABYLON.Tools.Warn("Function to remove was not found");
  83306. }
  83307. };
  83308. /**
  83309. * Register a function that will be executed after the physics step
  83310. */
  83311. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  83312. this._onAfterPhysicsStepCallbacks.push(func);
  83313. };
  83314. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  83315. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  83316. if (index > -1) {
  83317. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  83318. }
  83319. else {
  83320. BABYLON.Tools.Warn("Function to remove was not found");
  83321. }
  83322. };
  83323. /**
  83324. * register a function that will be executed when this impostor collides against a different body.
  83325. */
  83326. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  83327. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83328. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  83329. };
  83330. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  83331. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  83332. var index = -1;
  83333. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  83334. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  83335. // chcek the arrays match
  83336. var sameList = cbDef.otherImpostors.every(function (impostor) {
  83337. return collidedAgainstList.indexOf(impostor) > -1;
  83338. });
  83339. if (sameList) {
  83340. index = idx;
  83341. }
  83342. return sameList;
  83343. }
  83344. return false;
  83345. });
  83346. if (found) {
  83347. this._onPhysicsCollideCallbacks.splice(index, 1);
  83348. }
  83349. else {
  83350. BABYLON.Tools.Warn("Function to remove was not found");
  83351. }
  83352. };
  83353. PhysicsImpostor.prototype.getParentsRotation = function () {
  83354. var parent = this.object.parent;
  83355. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  83356. while (parent) {
  83357. if (parent.rotationQuaternion) {
  83358. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  83359. }
  83360. else {
  83361. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  83362. }
  83363. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  83364. parent = parent.parent;
  83365. }
  83366. return this._tmpQuat;
  83367. };
  83368. /**
  83369. * Apply a force
  83370. */
  83371. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  83372. if (this._physicsEngine) {
  83373. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  83374. }
  83375. return this;
  83376. };
  83377. /**
  83378. * Apply an impulse
  83379. */
  83380. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  83381. if (this._physicsEngine) {
  83382. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  83383. }
  83384. return this;
  83385. };
  83386. /**
  83387. * A help function to create a joint.
  83388. */
  83389. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  83390. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  83391. this.addJoint(otherImpostor, joint);
  83392. return this;
  83393. };
  83394. /**
  83395. * Add a joint to this impostor with a different impostor.
  83396. */
  83397. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  83398. this._joints.push({
  83399. otherImpostor: otherImpostor,
  83400. joint: joint
  83401. });
  83402. if (this._physicsEngine) {
  83403. this._physicsEngine.addJoint(this, otherImpostor, joint);
  83404. }
  83405. return this;
  83406. };
  83407. /**
  83408. * Will keep this body still, in a sleep mode.
  83409. */
  83410. PhysicsImpostor.prototype.sleep = function () {
  83411. if (this._physicsEngine) {
  83412. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  83413. }
  83414. return this;
  83415. };
  83416. /**
  83417. * Wake the body up.
  83418. */
  83419. PhysicsImpostor.prototype.wakeUp = function () {
  83420. if (this._physicsEngine) {
  83421. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  83422. }
  83423. return this;
  83424. };
  83425. PhysicsImpostor.prototype.clone = function (newObject) {
  83426. if (!newObject)
  83427. return null;
  83428. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  83429. };
  83430. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  83431. var _this = this;
  83432. //no dispose if no physics engine is available.
  83433. if (!this._physicsEngine) {
  83434. return;
  83435. }
  83436. this._joints.forEach(function (j) {
  83437. if (_this._physicsEngine) {
  83438. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  83439. }
  83440. });
  83441. //dispose the physics body
  83442. this._physicsEngine.removeImpostor(this);
  83443. if (this.parent) {
  83444. this.parent.forceUpdate();
  83445. }
  83446. else {
  83447. /*this._object.getChildMeshes().forEach(function(mesh) {
  83448. if (mesh.physicsImpostor) {
  83449. if (disposeChildren) {
  83450. mesh.physicsImpostor.dispose();
  83451. mesh.physicsImpostor = null;
  83452. }
  83453. }
  83454. })*/
  83455. }
  83456. this._isDisposed = true;
  83457. };
  83458. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  83459. this._deltaPosition.copyFrom(position);
  83460. };
  83461. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  83462. if (!this._deltaRotation) {
  83463. this._deltaRotation = new BABYLON.Quaternion();
  83464. }
  83465. this._deltaRotation.copyFrom(rotation);
  83466. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  83467. };
  83468. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  83469. if (this._physicsEngine) {
  83470. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  83471. }
  83472. return this;
  83473. };
  83474. PhysicsImpostor.prototype.getRadius = function () {
  83475. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  83476. };
  83477. /**
  83478. * Sync a bone with this impostor
  83479. * @param bone The bone to sync to the impostor.
  83480. * @param boneMesh The mesh that the bone is influencing.
  83481. * @param jointPivot The pivot of the joint / bone in local space.
  83482. * @param distToJoint Optional distance from the impostor to the joint.
  83483. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83484. */
  83485. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  83486. var tempVec = PhysicsImpostor._tmpVecs[0];
  83487. var mesh = this.object;
  83488. if (mesh.rotationQuaternion) {
  83489. if (adjustRotation) {
  83490. var tempQuat = PhysicsImpostor._tmpQuat;
  83491. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  83492. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  83493. }
  83494. else {
  83495. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  83496. }
  83497. }
  83498. tempVec.x = 0;
  83499. tempVec.y = 0;
  83500. tempVec.z = 0;
  83501. if (jointPivot) {
  83502. tempVec.x = jointPivot.x;
  83503. tempVec.y = jointPivot.y;
  83504. tempVec.z = jointPivot.z;
  83505. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  83506. if (distToJoint === undefined || distToJoint === null) {
  83507. distToJoint = jointPivot.length();
  83508. }
  83509. tempVec.x *= distToJoint;
  83510. tempVec.y *= distToJoint;
  83511. tempVec.z *= distToJoint;
  83512. }
  83513. if (bone.getParent()) {
  83514. tempVec.addInPlace(mesh.getAbsolutePosition());
  83515. bone.setAbsolutePosition(tempVec, boneMesh);
  83516. }
  83517. else {
  83518. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  83519. boneMesh.position.x -= tempVec.x;
  83520. boneMesh.position.y -= tempVec.y;
  83521. boneMesh.position.z -= tempVec.z;
  83522. }
  83523. };
  83524. /**
  83525. * Sync impostor to a bone
  83526. * @param bone The bone that the impostor will be synced to.
  83527. * @param boneMesh The mesh that the bone is influencing.
  83528. * @param jointPivot The pivot of the joint / bone in local space.
  83529. * @param distToJoint Optional distance from the impostor to the joint.
  83530. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  83531. * @param boneAxis Optional vector3 axis the bone is aligned with
  83532. */
  83533. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  83534. var mesh = this.object;
  83535. if (mesh.rotationQuaternion) {
  83536. if (adjustRotation) {
  83537. var tempQuat = PhysicsImpostor._tmpQuat;
  83538. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  83539. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  83540. }
  83541. else {
  83542. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  83543. }
  83544. }
  83545. var pos = PhysicsImpostor._tmpVecs[0];
  83546. var boneDir = PhysicsImpostor._tmpVecs[1];
  83547. if (!boneAxis) {
  83548. boneAxis = PhysicsImpostor._tmpVecs[2];
  83549. boneAxis.x = 0;
  83550. boneAxis.y = 1;
  83551. boneAxis.z = 0;
  83552. }
  83553. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  83554. bone.getAbsolutePositionToRef(boneMesh, pos);
  83555. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  83556. distToJoint = jointPivot.length();
  83557. }
  83558. if (distToJoint !== undefined && distToJoint !== null) {
  83559. pos.x += boneDir.x * distToJoint;
  83560. pos.y += boneDir.y * distToJoint;
  83561. pos.z += boneDir.z * distToJoint;
  83562. }
  83563. mesh.setAbsolutePosition(pos);
  83564. };
  83565. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  83566. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  83567. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83568. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  83569. //Impostor types
  83570. PhysicsImpostor.NoImpostor = 0;
  83571. PhysicsImpostor.SphereImpostor = 1;
  83572. PhysicsImpostor.BoxImpostor = 2;
  83573. PhysicsImpostor.PlaneImpostor = 3;
  83574. PhysicsImpostor.MeshImpostor = 4;
  83575. PhysicsImpostor.CylinderImpostor = 7;
  83576. PhysicsImpostor.ParticleImpostor = 8;
  83577. PhysicsImpostor.HeightmapImpostor = 9;
  83578. return PhysicsImpostor;
  83579. }());
  83580. BABYLON.PhysicsImpostor = PhysicsImpostor;
  83581. })(BABYLON || (BABYLON = {}));
  83582. //# sourceMappingURL=babylon.physicsImpostor.js.map
  83583. var BABYLON;
  83584. (function (BABYLON) {
  83585. var PhysicsEngine = /** @class */ (function () {
  83586. function PhysicsEngine(gravity, _physicsPlugin) {
  83587. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83588. this._physicsPlugin = _physicsPlugin;
  83589. //new methods and parameters
  83590. this._impostors = [];
  83591. this._joints = [];
  83592. if (!this._physicsPlugin.isSupported()) {
  83593. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83594. + "Please make sure it is included.");
  83595. }
  83596. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83597. this.setGravity(gravity);
  83598. this.setTimeStep();
  83599. }
  83600. PhysicsEngine.prototype.setGravity = function (gravity) {
  83601. this.gravity = gravity;
  83602. this._physicsPlugin.setGravity(this.gravity);
  83603. };
  83604. /**
  83605. * Set the time step of the physics engine.
  83606. * default is 1/60.
  83607. * To slow it down, enter 1/600 for example.
  83608. * To speed it up, 1/30
  83609. * @param {number} newTimeStep the new timestep to apply to this world.
  83610. */
  83611. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83612. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83613. this._physicsPlugin.setTimeStep(newTimeStep);
  83614. };
  83615. /**
  83616. * Get the time step of the physics engine.
  83617. */
  83618. PhysicsEngine.prototype.getTimeStep = function () {
  83619. return this._physicsPlugin.getTimeStep();
  83620. };
  83621. PhysicsEngine.prototype.dispose = function () {
  83622. this._impostors.forEach(function (impostor) {
  83623. impostor.dispose();
  83624. });
  83625. this._physicsPlugin.dispose();
  83626. };
  83627. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83628. return this._physicsPlugin.name;
  83629. };
  83630. /**
  83631. * Adding a new impostor for the impostor tracking.
  83632. * This will be done by the impostor itself.
  83633. * @param {PhysicsImpostor} impostor the impostor to add
  83634. */
  83635. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83636. impostor.uniqueId = this._impostors.push(impostor);
  83637. //if no parent, generate the body
  83638. if (!impostor.parent) {
  83639. this._physicsPlugin.generatePhysicsBody(impostor);
  83640. }
  83641. };
  83642. /**
  83643. * Remove an impostor from the engine.
  83644. * This impostor and its mesh will not longer be updated by the physics engine.
  83645. * @param {PhysicsImpostor} impostor the impostor to remove
  83646. */
  83647. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83648. var index = this._impostors.indexOf(impostor);
  83649. if (index > -1) {
  83650. var removed = this._impostors.splice(index, 1);
  83651. //Is it needed?
  83652. if (removed.length) {
  83653. //this will also remove it from the world.
  83654. removed[0].physicsBody = null;
  83655. }
  83656. }
  83657. };
  83658. /**
  83659. * Add a joint to the physics engine
  83660. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83661. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83662. * @param {PhysicsJoint} the joint that will connect both impostors.
  83663. */
  83664. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83665. var impostorJoint = {
  83666. mainImpostor: mainImpostor,
  83667. connectedImpostor: connectedImpostor,
  83668. joint: joint
  83669. };
  83670. joint.physicsPlugin = this._physicsPlugin;
  83671. this._joints.push(impostorJoint);
  83672. this._physicsPlugin.generateJoint(impostorJoint);
  83673. };
  83674. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83675. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83676. return (impostorJoint.connectedImpostor === connectedImpostor
  83677. && impostorJoint.joint === joint
  83678. && impostorJoint.mainImpostor === mainImpostor);
  83679. });
  83680. if (matchingJoints.length) {
  83681. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83682. //TODO remove it from the list as well
  83683. }
  83684. };
  83685. /**
  83686. * Called by the scene. no need to call it.
  83687. */
  83688. PhysicsEngine.prototype._step = function (delta) {
  83689. var _this = this;
  83690. //check if any mesh has no body / requires an update
  83691. this._impostors.forEach(function (impostor) {
  83692. if (impostor.isBodyInitRequired()) {
  83693. _this._physicsPlugin.generatePhysicsBody(impostor);
  83694. }
  83695. });
  83696. if (delta > 0.1) {
  83697. delta = 0.1;
  83698. }
  83699. else if (delta <= 0) {
  83700. delta = 1.0 / 60.0;
  83701. }
  83702. this._physicsPlugin.executeStep(delta, this._impostors);
  83703. };
  83704. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83705. return this._physicsPlugin;
  83706. };
  83707. PhysicsEngine.prototype.getImpostors = function () {
  83708. return this._impostors;
  83709. };
  83710. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83711. for (var i = 0; i < this._impostors.length; ++i) {
  83712. if (this._impostors[i].object === object) {
  83713. return this._impostors[i];
  83714. }
  83715. }
  83716. return null;
  83717. };
  83718. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83719. for (var i = 0; i < this._impostors.length; ++i) {
  83720. if (this._impostors[i].physicsBody === body) {
  83721. return this._impostors[i];
  83722. }
  83723. }
  83724. return null;
  83725. };
  83726. // Statics
  83727. PhysicsEngine.Epsilon = 0.001;
  83728. return PhysicsEngine;
  83729. }());
  83730. BABYLON.PhysicsEngine = PhysicsEngine;
  83731. })(BABYLON || (BABYLON = {}));
  83732. //# sourceMappingURL=babylon.physicsEngine.js.map
  83733. var BABYLON;
  83734. (function (BABYLON) {
  83735. var PhysicsHelper = /** @class */ (function () {
  83736. function PhysicsHelper(scene) {
  83737. this._scene = scene;
  83738. this._physicsEngine = this._scene.getPhysicsEngine();
  83739. if (!this._physicsEngine) {
  83740. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83741. }
  83742. }
  83743. /**
  83744. * @param {Vector3} origin the origin of the explosion
  83745. * @param {number} radius the explosion radius
  83746. * @param {number} strength the explosion strength
  83747. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83748. */
  83749. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83750. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83751. if (!this._physicsEngine) {
  83752. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83753. return null;
  83754. }
  83755. var impostors = this._physicsEngine.getImpostors();
  83756. if (impostors.length === 0) {
  83757. return null;
  83758. }
  83759. var event = new PhysicsRadialExplosionEvent(this._scene);
  83760. impostors.forEach(function (impostor) {
  83761. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83762. if (!impostorForceAndContactPoint) {
  83763. return;
  83764. }
  83765. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83766. });
  83767. event.dispose(false);
  83768. return event;
  83769. };
  83770. /**
  83771. * @param {Vector3} origin the origin of the explosion
  83772. * @param {number} radius the explosion radius
  83773. * @param {number} strength the explosion strength
  83774. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83775. */
  83776. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83777. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83778. if (!this._physicsEngine) {
  83779. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83780. return null;
  83781. }
  83782. var impostors = this._physicsEngine.getImpostors();
  83783. if (impostors.length === 0) {
  83784. return null;
  83785. }
  83786. var event = new PhysicsRadialExplosionEvent(this._scene);
  83787. impostors.forEach(function (impostor) {
  83788. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83789. if (!impostorForceAndContactPoint) {
  83790. return;
  83791. }
  83792. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83793. });
  83794. event.dispose(false);
  83795. return event;
  83796. };
  83797. /**
  83798. * @param {Vector3} origin the origin of the explosion
  83799. * @param {number} radius the explosion radius
  83800. * @param {number} strength the explosion strength
  83801. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83802. */
  83803. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83804. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83805. if (!this._physicsEngine) {
  83806. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83807. return null;
  83808. }
  83809. var impostors = this._physicsEngine.getImpostors();
  83810. if (impostors.length === 0) {
  83811. return null;
  83812. }
  83813. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83814. event.dispose(false);
  83815. return event;
  83816. };
  83817. /**
  83818. * @param {Vector3} origin the origin of the updraft
  83819. * @param {number} radius the radius of the updraft
  83820. * @param {number} strength the strength of the updraft
  83821. * @param {number} height the height of the updraft
  83822. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83823. */
  83824. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83825. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83826. if (!this._physicsEngine) {
  83827. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83828. return null;
  83829. }
  83830. if (this._physicsEngine.getImpostors().length === 0) {
  83831. return null;
  83832. }
  83833. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83834. event.dispose(false);
  83835. return event;
  83836. };
  83837. /**
  83838. * @param {Vector3} origin the of the vortex
  83839. * @param {number} radius the radius of the vortex
  83840. * @param {number} strength the strength of the vortex
  83841. * @param {number} height the height of the vortex
  83842. */
  83843. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83844. if (!this._physicsEngine) {
  83845. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83846. return null;
  83847. }
  83848. if (this._physicsEngine.getImpostors().length === 0) {
  83849. return null;
  83850. }
  83851. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83852. event.dispose(false);
  83853. return event;
  83854. };
  83855. return PhysicsHelper;
  83856. }());
  83857. BABYLON.PhysicsHelper = PhysicsHelper;
  83858. /***** Radial explosion *****/
  83859. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83860. function PhysicsRadialExplosionEvent(scene) {
  83861. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83862. this._rays = [];
  83863. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83864. this._scene = scene;
  83865. }
  83866. /**
  83867. * Returns the data related to the radial explosion event (sphere & rays).
  83868. * @returns {PhysicsRadialExplosionEventData}
  83869. */
  83870. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83871. this._dataFetched = true;
  83872. return {
  83873. sphere: this._sphere,
  83874. rays: this._rays,
  83875. };
  83876. };
  83877. /**
  83878. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83879. * @param impostor
  83880. * @param {Vector3} origin the origin of the explosion
  83881. * @param {number} radius the explosion radius
  83882. * @param {number} strength the explosion strength
  83883. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83884. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83885. */
  83886. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83887. if (impostor.mass === 0) {
  83888. return null;
  83889. }
  83890. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83891. return null;
  83892. }
  83893. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83894. return null;
  83895. }
  83896. var impostorObjectCenter = impostor.getObjectCenter();
  83897. var direction = impostorObjectCenter.subtract(origin);
  83898. var ray = new BABYLON.Ray(origin, direction, radius);
  83899. this._rays.push(ray);
  83900. var hit = ray.intersectsMesh(impostor.object);
  83901. var contactPoint = hit.pickedPoint;
  83902. if (!contactPoint) {
  83903. return null;
  83904. }
  83905. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83906. if (distanceFromOrigin > radius) {
  83907. return null;
  83908. }
  83909. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83910. ? strength
  83911. : strength * (1 - (distanceFromOrigin / radius));
  83912. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83913. return { force: force, contactPoint: contactPoint };
  83914. };
  83915. /**
  83916. * Disposes the sphere.
  83917. * @param {bolean} force
  83918. */
  83919. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83920. var _this = this;
  83921. if (force === void 0) { force = true; }
  83922. if (force) {
  83923. this._sphere.dispose();
  83924. }
  83925. else {
  83926. setTimeout(function () {
  83927. if (!_this._dataFetched) {
  83928. _this._sphere.dispose();
  83929. }
  83930. }, 0);
  83931. }
  83932. };
  83933. /*** Helpers ***/
  83934. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83935. if (!this._sphere) {
  83936. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83937. this._sphere.isVisible = false;
  83938. }
  83939. };
  83940. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83941. var impostorObject = impostor.object;
  83942. this._prepareSphere();
  83943. this._sphere.position = origin;
  83944. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83945. this._sphere._updateBoundingInfo();
  83946. this._sphere.computeWorldMatrix(true);
  83947. return this._sphere.intersectsMesh(impostorObject, true);
  83948. };
  83949. return PhysicsRadialExplosionEvent;
  83950. }());
  83951. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83952. /***** Gravitational Field *****/
  83953. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83954. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83955. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83956. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83957. this._physicsHelper = physicsHelper;
  83958. this._scene = scene;
  83959. this._origin = origin;
  83960. this._radius = radius;
  83961. this._strength = strength;
  83962. this._falloff = falloff;
  83963. this._tickCallback = this._tick.bind(this);
  83964. }
  83965. /**
  83966. * Returns the data related to the gravitational field event (sphere).
  83967. * @returns {PhysicsGravitationalFieldEventData}
  83968. */
  83969. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83970. this._dataFetched = true;
  83971. return {
  83972. sphere: this._sphere,
  83973. };
  83974. };
  83975. /**
  83976. * Enables the gravitational field.
  83977. */
  83978. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83979. this._tickCallback.call(this);
  83980. this._scene.registerBeforeRender(this._tickCallback);
  83981. };
  83982. /**
  83983. * Disables the gravitational field.
  83984. */
  83985. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83986. this._scene.unregisterBeforeRender(this._tickCallback);
  83987. };
  83988. /**
  83989. * Disposes the sphere.
  83990. * @param {bolean} force
  83991. */
  83992. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83993. var _this = this;
  83994. if (force === void 0) { force = true; }
  83995. if (force) {
  83996. this._sphere.dispose();
  83997. }
  83998. else {
  83999. setTimeout(function () {
  84000. if (!_this._dataFetched) {
  84001. _this._sphere.dispose();
  84002. }
  84003. }, 0);
  84004. }
  84005. };
  84006. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84007. // Since the params won't change, we fetch the event only once
  84008. if (this._sphere) {
  84009. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84010. }
  84011. else {
  84012. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84013. if (radialExplosionEvent) {
  84014. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84015. }
  84016. }
  84017. };
  84018. return PhysicsGravitationalFieldEvent;
  84019. }());
  84020. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84021. /***** Updraft *****/
  84022. var PhysicsUpdraftEvent = /** @class */ (function () {
  84023. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84024. this._scene = _scene;
  84025. this._origin = _origin;
  84026. this._radius = _radius;
  84027. this._strength = _strength;
  84028. this._height = _height;
  84029. this._updraftMode = _updraftMode;
  84030. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84031. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84032. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84033. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84034. this._physicsEngine = this._scene.getPhysicsEngine();
  84035. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84036. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84037. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84038. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84039. }
  84040. this._tickCallback = this._tick.bind(this);
  84041. }
  84042. /**
  84043. * Returns the data related to the updraft event (cylinder).
  84044. * @returns {PhysicsUpdraftEventData}
  84045. */
  84046. PhysicsUpdraftEvent.prototype.getData = function () {
  84047. this._dataFetched = true;
  84048. return {
  84049. cylinder: this._cylinder,
  84050. };
  84051. };
  84052. /**
  84053. * Enables the updraft.
  84054. */
  84055. PhysicsUpdraftEvent.prototype.enable = function () {
  84056. this._tickCallback.call(this);
  84057. this._scene.registerBeforeRender(this._tickCallback);
  84058. };
  84059. /**
  84060. * Disables the cortex.
  84061. */
  84062. PhysicsUpdraftEvent.prototype.disable = function () {
  84063. this._scene.unregisterBeforeRender(this._tickCallback);
  84064. };
  84065. /**
  84066. * Disposes the sphere.
  84067. * @param {bolean} force
  84068. */
  84069. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84070. var _this = this;
  84071. if (force === void 0) { force = true; }
  84072. if (force) {
  84073. this._cylinder.dispose();
  84074. }
  84075. else {
  84076. setTimeout(function () {
  84077. if (!_this._dataFetched) {
  84078. _this._cylinder.dispose();
  84079. }
  84080. }, 0);
  84081. }
  84082. };
  84083. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84084. if (impostor.mass === 0) {
  84085. return null;
  84086. }
  84087. if (!this._intersectsWithCylinder(impostor)) {
  84088. return null;
  84089. }
  84090. var impostorObjectCenter = impostor.getObjectCenter();
  84091. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84092. var direction = this._originDirection;
  84093. }
  84094. else {
  84095. var direction = impostorObjectCenter.subtract(this._originTop);
  84096. }
  84097. var multiplier = this._strength * -1;
  84098. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84099. return { force: force, contactPoint: impostorObjectCenter };
  84100. };
  84101. PhysicsUpdraftEvent.prototype._tick = function () {
  84102. var _this = this;
  84103. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84104. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84105. if (!impostorForceAndContactPoint) {
  84106. return;
  84107. }
  84108. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84109. });
  84110. };
  84111. /*** Helpers ***/
  84112. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84113. if (!this._cylinder) {
  84114. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84115. height: this._height,
  84116. diameter: this._radius * 2,
  84117. }, this._scene);
  84118. this._cylinder.isVisible = false;
  84119. }
  84120. };
  84121. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84122. var impostorObject = impostor.object;
  84123. this._prepareCylinder();
  84124. this._cylinder.position = this._cylinderPosition;
  84125. return this._cylinder.intersectsMesh(impostorObject, true);
  84126. };
  84127. return PhysicsUpdraftEvent;
  84128. }());
  84129. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84130. /***** Vortex *****/
  84131. var PhysicsVortexEvent = /** @class */ (function () {
  84132. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  84133. this._scene = _scene;
  84134. this._origin = _origin;
  84135. this._radius = _radius;
  84136. this._strength = _strength;
  84137. this._height = _height;
  84138. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84139. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  84140. this._updraftMultiplier = 0.02;
  84141. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84142. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84143. this._physicsEngine = this._scene.getPhysicsEngine();
  84144. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84145. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84146. this._tickCallback = this._tick.bind(this);
  84147. }
  84148. /**
  84149. * Returns the data related to the vortex event (cylinder).
  84150. * @returns {PhysicsVortexEventData}
  84151. */
  84152. PhysicsVortexEvent.prototype.getData = function () {
  84153. this._dataFetched = true;
  84154. return {
  84155. cylinder: this._cylinder,
  84156. };
  84157. };
  84158. /**
  84159. * Enables the vortex.
  84160. */
  84161. PhysicsVortexEvent.prototype.enable = function () {
  84162. this._tickCallback.call(this);
  84163. this._scene.registerBeforeRender(this._tickCallback);
  84164. };
  84165. /**
  84166. * Disables the cortex.
  84167. */
  84168. PhysicsVortexEvent.prototype.disable = function () {
  84169. this._scene.unregisterBeforeRender(this._tickCallback);
  84170. };
  84171. /**
  84172. * Disposes the sphere.
  84173. * @param {bolean} force
  84174. */
  84175. PhysicsVortexEvent.prototype.dispose = function (force) {
  84176. var _this = this;
  84177. if (force === void 0) { force = true; }
  84178. if (force) {
  84179. this._cylinder.dispose();
  84180. }
  84181. else {
  84182. setTimeout(function () {
  84183. if (!_this._dataFetched) {
  84184. _this._cylinder.dispose();
  84185. }
  84186. }, 0);
  84187. }
  84188. };
  84189. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84190. if (impostor.mass === 0) {
  84191. return null;
  84192. }
  84193. if (!this._intersectsWithCylinder(impostor)) {
  84194. return null;
  84195. }
  84196. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84197. return null;
  84198. }
  84199. var impostorObjectCenter = impostor.getObjectCenter();
  84200. 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)
  84201. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  84202. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  84203. var hit = ray.intersectsMesh(impostor.object);
  84204. var contactPoint = hit.pickedPoint;
  84205. if (!contactPoint) {
  84206. return null;
  84207. }
  84208. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  84209. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  84210. var directionToOrigin = contactPoint.normalize();
  84211. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84212. directionToOrigin = directionToOrigin.negate();
  84213. }
  84214. // TODO: find a more physically based solution
  84215. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  84216. var forceX = directionToOrigin.x * this._strength / 8;
  84217. var forceY = directionToOrigin.y * this._updraftMultiplier;
  84218. var forceZ = directionToOrigin.z * this._strength / 8;
  84219. }
  84220. else {
  84221. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  84222. var forceY = this._originTop.y * this._updraftMultiplier;
  84223. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  84224. }
  84225. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  84226. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  84227. return { force: force, contactPoint: impostorObjectCenter };
  84228. };
  84229. PhysicsVortexEvent.prototype._tick = function () {
  84230. var _this = this;
  84231. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84232. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84233. if (!impostorForceAndContactPoint) {
  84234. return;
  84235. }
  84236. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84237. });
  84238. };
  84239. /*** Helpers ***/
  84240. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  84241. if (!this._cylinder) {
  84242. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  84243. height: this._height,
  84244. diameter: this._radius * 2,
  84245. }, this._scene);
  84246. this._cylinder.isVisible = false;
  84247. }
  84248. };
  84249. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  84250. var impostorObject = impostor.object;
  84251. this._prepareCylinder();
  84252. this._cylinder.position = this._cylinderPosition;
  84253. return this._cylinder.intersectsMesh(impostorObject, true);
  84254. };
  84255. return PhysicsVortexEvent;
  84256. }());
  84257. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  84258. /***** Enums *****/
  84259. /**
  84260. * The strenght of the force in correspondence to the distance of the affected object
  84261. */
  84262. var PhysicsRadialImpulseFalloff;
  84263. (function (PhysicsRadialImpulseFalloff) {
  84264. /** Defines that impulse is constant in strength across it's whole radius */
  84265. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  84266. /** DEfines that impulse gets weaker if it's further from the origin */
  84267. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  84268. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  84269. /**
  84270. * The strenght of the force in correspondence to the distance of the affected object
  84271. */
  84272. var PhysicsUpdraftMode;
  84273. (function (PhysicsUpdraftMode) {
  84274. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  84275. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  84276. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  84277. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  84278. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  84279. })(BABYLON || (BABYLON = {}));
  84280. //# sourceMappingURL=babylon.physicsHelper.js.map
  84281. var BABYLON;
  84282. (function (BABYLON) {
  84283. var CannonJSPlugin = /** @class */ (function () {
  84284. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  84285. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  84286. if (iterations === void 0) { iterations = 10; }
  84287. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  84288. this.name = "CannonJSPlugin";
  84289. this._physicsMaterials = new Array();
  84290. this._fixedTimeStep = 1 / 60;
  84291. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  84292. this.BJSCANNON = CANNON;
  84293. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  84294. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  84295. this._tmpPosition = BABYLON.Vector3.Zero();
  84296. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  84297. this._tmpUnityRotation = new BABYLON.Quaternion();
  84298. if (!this.isSupported()) {
  84299. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  84300. return;
  84301. }
  84302. this._extendNamespace();
  84303. this.world = new this.BJSCANNON.World();
  84304. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  84305. this.world.solver.iterations = iterations;
  84306. }
  84307. CannonJSPlugin.prototype.setGravity = function (gravity) {
  84308. this.world.gravity.copy(gravity);
  84309. };
  84310. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  84311. this._fixedTimeStep = timeStep;
  84312. };
  84313. CannonJSPlugin.prototype.getTimeStep = function () {
  84314. return this._fixedTimeStep;
  84315. };
  84316. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  84317. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  84318. };
  84319. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84320. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84321. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84322. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  84323. };
  84324. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84325. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  84326. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  84327. impostor.physicsBody.applyForce(impulse, worldPoint);
  84328. };
  84329. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84330. //parent-child relationship. Does this impostor has a parent impostor?
  84331. if (impostor.parent) {
  84332. if (impostor.physicsBody) {
  84333. this.removePhysicsBody(impostor);
  84334. //TODO is that needed?
  84335. impostor.forceUpdate();
  84336. }
  84337. return;
  84338. }
  84339. //should a new body be created for this impostor?
  84340. if (impostor.isBodyInitRequired()) {
  84341. var shape = this._createShape(impostor);
  84342. //unregister events, if body is being changed
  84343. var oldBody = impostor.physicsBody;
  84344. if (oldBody) {
  84345. this.removePhysicsBody(impostor);
  84346. }
  84347. //create the body and material
  84348. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  84349. var bodyCreationObject = {
  84350. mass: impostor.getParam("mass"),
  84351. material: material
  84352. };
  84353. // A simple extend, in case native options were used.
  84354. var nativeOptions = impostor.getParam("nativeOptions");
  84355. for (var key in nativeOptions) {
  84356. if (nativeOptions.hasOwnProperty(key)) {
  84357. bodyCreationObject[key] = nativeOptions[key];
  84358. }
  84359. }
  84360. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  84361. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  84362. this.world.addEventListener("preStep", impostor.beforeStep);
  84363. this.world.addEventListener("postStep", impostor.afterStep);
  84364. impostor.physicsBody.addShape(shape);
  84365. this.world.add(impostor.physicsBody);
  84366. //try to keep the body moving in the right direction by taking old properties.
  84367. //Should be tested!
  84368. if (oldBody) {
  84369. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  84370. impostor.physicsBody[param].copy(oldBody[param]);
  84371. });
  84372. }
  84373. this._processChildMeshes(impostor);
  84374. }
  84375. //now update the body's transformation
  84376. this._updatePhysicsBodyTransformation(impostor);
  84377. };
  84378. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  84379. var _this = this;
  84380. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  84381. var currentRotation = mainImpostor.object.rotationQuaternion;
  84382. if (meshChildren.length) {
  84383. var processMesh = function (localPosition, mesh) {
  84384. if (!currentRotation || !mesh.rotationQuaternion) {
  84385. return;
  84386. }
  84387. var childImpostor = mesh.getPhysicsImpostor();
  84388. if (childImpostor) {
  84389. var parent = childImpostor.parent;
  84390. if (parent !== mainImpostor) {
  84391. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  84392. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  84393. if (childImpostor.physicsBody) {
  84394. _this.removePhysicsBody(childImpostor);
  84395. childImpostor.physicsBody = null;
  84396. }
  84397. childImpostor.parent = mainImpostor;
  84398. childImpostor.resetUpdateFlags();
  84399. 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));
  84400. //Add the mass of the children.
  84401. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  84402. }
  84403. }
  84404. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  84405. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  84406. };
  84407. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  84408. }
  84409. };
  84410. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84411. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  84412. this.world.removeEventListener("preStep", impostor.beforeStep);
  84413. this.world.removeEventListener("postStep", impostor.afterStep);
  84414. this.world.remove(impostor.physicsBody);
  84415. };
  84416. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84417. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84418. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84419. if (!mainBody || !connectedBody) {
  84420. return;
  84421. }
  84422. var constraint;
  84423. var jointData = impostorJoint.joint.jointData;
  84424. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  84425. var constraintData = {
  84426. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  84427. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  84428. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  84429. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  84430. maxForce: jointData.nativeParams.maxForce,
  84431. collideConnected: !!jointData.collision
  84432. };
  84433. switch (impostorJoint.joint.type) {
  84434. case BABYLON.PhysicsJoint.HingeJoint:
  84435. case BABYLON.PhysicsJoint.Hinge2Joint:
  84436. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  84437. break;
  84438. case BABYLON.PhysicsJoint.DistanceJoint:
  84439. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  84440. break;
  84441. case BABYLON.PhysicsJoint.SpringJoint:
  84442. var springData = jointData;
  84443. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  84444. restLength: springData.length,
  84445. stiffness: springData.stiffness,
  84446. damping: springData.damping,
  84447. localAnchorA: constraintData.pivotA,
  84448. localAnchorB: constraintData.pivotB
  84449. });
  84450. break;
  84451. case BABYLON.PhysicsJoint.LockJoint:
  84452. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  84453. break;
  84454. case BABYLON.PhysicsJoint.PointToPointJoint:
  84455. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84456. default:
  84457. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  84458. break;
  84459. }
  84460. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  84461. constraint.collideConnected = !!jointData.collision;
  84462. impostorJoint.joint.physicsJoint = constraint;
  84463. //don't add spring as constraint, as it is not one.
  84464. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  84465. this.world.addConstraint(constraint);
  84466. }
  84467. else {
  84468. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  84469. constraint.applyForce();
  84470. });
  84471. }
  84472. };
  84473. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84474. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  84475. };
  84476. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  84477. var index;
  84478. var mat;
  84479. for (index = 0; index < this._physicsMaterials.length; index++) {
  84480. mat = this._physicsMaterials[index];
  84481. if (mat.friction === friction && mat.restitution === restitution) {
  84482. return mat;
  84483. }
  84484. }
  84485. var currentMat = new this.BJSCANNON.Material(name);
  84486. currentMat.friction = friction;
  84487. currentMat.restitution = restitution;
  84488. this._physicsMaterials.push(currentMat);
  84489. return currentMat;
  84490. };
  84491. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  84492. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  84493. };
  84494. CannonJSPlugin.prototype._createShape = function (impostor) {
  84495. var object = impostor.object;
  84496. var returnValue;
  84497. var extendSize = impostor.getObjectExtendSize();
  84498. switch (impostor.type) {
  84499. case BABYLON.PhysicsImpostor.SphereImpostor:
  84500. var radiusX = extendSize.x;
  84501. var radiusY = extendSize.y;
  84502. var radiusZ = extendSize.z;
  84503. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  84504. break;
  84505. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  84506. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84507. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  84508. break;
  84509. case BABYLON.PhysicsImpostor.BoxImpostor:
  84510. var box = extendSize.scale(0.5);
  84511. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  84512. break;
  84513. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84514. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  84515. returnValue = new this.BJSCANNON.Plane();
  84516. break;
  84517. case BABYLON.PhysicsImpostor.MeshImpostor:
  84518. // should transform the vertex data to world coordinates!!
  84519. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  84520. var rawFaces = object.getIndices ? object.getIndices() : [];
  84521. if (!rawVerts)
  84522. return;
  84523. // get only scale! so the object could transform correctly.
  84524. var oldPosition = object.position.clone();
  84525. var oldRotation = object.rotation && object.rotation.clone();
  84526. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  84527. object.position.copyFromFloats(0, 0, 0);
  84528. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84529. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84530. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84531. var transform = object.computeWorldMatrix(true);
  84532. // convert rawVerts to object space
  84533. var temp = new Array();
  84534. var index;
  84535. for (index = 0; index < rawVerts.length; index += 3) {
  84536. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  84537. }
  84538. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  84539. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  84540. //now set back the transformation!
  84541. object.position.copyFrom(oldPosition);
  84542. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  84543. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  84544. break;
  84545. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  84546. var oldPosition2 = object.position.clone();
  84547. var oldRotation2 = object.rotation && object.rotation.clone();
  84548. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  84549. object.position.copyFromFloats(0, 0, 0);
  84550. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  84551. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  84552. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  84553. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  84554. returnValue = this._createHeightmap(object);
  84555. object.position.copyFrom(oldPosition2);
  84556. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  84557. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  84558. object.computeWorldMatrix(true);
  84559. break;
  84560. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84561. returnValue = new this.BJSCANNON.Particle();
  84562. break;
  84563. }
  84564. return returnValue;
  84565. };
  84566. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  84567. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  84568. var transform = object.computeWorldMatrix(true);
  84569. // convert rawVerts to object space
  84570. var temp = new Array();
  84571. var index;
  84572. for (index = 0; index < pos.length; index += 3) {
  84573. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  84574. }
  84575. pos = temp;
  84576. var matrix = new Array();
  84577. //For now pointDepth will not be used and will be automatically calculated.
  84578. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  84579. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  84580. var boundingInfo = object.getBoundingInfo();
  84581. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  84582. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  84583. var elementSize = dim * 2 / arraySize;
  84584. for (var i = 0; i < pos.length; i = i + 3) {
  84585. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  84586. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  84587. var y = -pos[i + 2] + minY;
  84588. if (!matrix[x]) {
  84589. matrix[x] = [];
  84590. }
  84591. if (!matrix[x][z]) {
  84592. matrix[x][z] = y;
  84593. }
  84594. matrix[x][z] = Math.max(y, matrix[x][z]);
  84595. }
  84596. for (var x = 0; x <= arraySize; ++x) {
  84597. if (!matrix[x]) {
  84598. var loc = 1;
  84599. while (!matrix[(x + loc) % arraySize]) {
  84600. loc++;
  84601. }
  84602. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84603. //console.log("missing x", x);
  84604. }
  84605. for (var z = 0; z <= arraySize; ++z) {
  84606. if (!matrix[x][z]) {
  84607. var loc = 1;
  84608. var newValue;
  84609. while (newValue === undefined) {
  84610. newValue = matrix[x][(z + loc++) % arraySize];
  84611. }
  84612. matrix[x][z] = newValue;
  84613. }
  84614. }
  84615. }
  84616. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84617. elementSize: elementSize
  84618. });
  84619. //For future reference, needed for body transformation
  84620. shape.minY = minY;
  84621. return shape;
  84622. };
  84623. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84624. var object = impostor.object;
  84625. //make sure it is updated...
  84626. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84627. // The delta between the mesh position and the mesh bounding box center
  84628. var bInfo = object.getBoundingInfo();
  84629. if (!bInfo)
  84630. return;
  84631. var center = impostor.getObjectCenter();
  84632. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84633. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84634. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84635. this._tmpPosition.copyFrom(center);
  84636. var quaternion = object.rotationQuaternion;
  84637. if (!quaternion) {
  84638. return;
  84639. }
  84640. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84641. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84642. //-90 DEG in X, precalculated
  84643. quaternion = quaternion.multiply(this._minus90X);
  84644. //Invert! (Precalculated, 90 deg in X)
  84645. //No need to clone. this will never change.
  84646. impostor.setDeltaRotation(this._plus90X);
  84647. }
  84648. //If it is a heightfield, if should be centered.
  84649. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84650. var mesh = object;
  84651. var boundingInfo = mesh.getBoundingInfo();
  84652. //calculate the correct body position:
  84653. var rotationQuaternion = mesh.rotationQuaternion;
  84654. mesh.rotationQuaternion = this._tmpUnityRotation;
  84655. mesh.computeWorldMatrix(true);
  84656. //get original center with no rotation
  84657. var c = center.clone();
  84658. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84659. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84660. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84661. mesh.setPreTransformMatrix(p);
  84662. mesh.computeWorldMatrix(true);
  84663. //calculate the translation
  84664. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84665. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84666. //add it inverted to the delta
  84667. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84668. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84669. //rotation is back
  84670. mesh.rotationQuaternion = rotationQuaternion;
  84671. mesh.setPreTransformMatrix(oldPivot);
  84672. mesh.computeWorldMatrix(true);
  84673. }
  84674. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84675. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84676. //this._tmpPosition.copyFrom(object.position);
  84677. }
  84678. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84679. //Now update the impostor object
  84680. impostor.physicsBody.position.copy(this._tmpPosition);
  84681. impostor.physicsBody.quaternion.copy(quaternion);
  84682. };
  84683. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84684. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84685. if (impostor.object.rotationQuaternion) {
  84686. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84687. }
  84688. };
  84689. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84690. impostor.physicsBody.position.copy(newPosition);
  84691. impostor.physicsBody.quaternion.copy(newRotation);
  84692. };
  84693. CannonJSPlugin.prototype.isSupported = function () {
  84694. return this.BJSCANNON !== undefined;
  84695. };
  84696. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84697. impostor.physicsBody.velocity.copy(velocity);
  84698. };
  84699. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84700. impostor.physicsBody.angularVelocity.copy(velocity);
  84701. };
  84702. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84703. var v = impostor.physicsBody.velocity;
  84704. if (!v) {
  84705. return null;
  84706. }
  84707. return new BABYLON.Vector3(v.x, v.y, v.z);
  84708. };
  84709. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84710. var v = impostor.physicsBody.angularVelocity;
  84711. if (!v) {
  84712. return null;
  84713. }
  84714. return new BABYLON.Vector3(v.x, v.y, v.z);
  84715. };
  84716. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84717. impostor.physicsBody.mass = mass;
  84718. impostor.physicsBody.updateMassProperties();
  84719. };
  84720. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84721. return impostor.physicsBody.mass;
  84722. };
  84723. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84724. return impostor.physicsBody.material.friction;
  84725. };
  84726. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84727. impostor.physicsBody.material.friction = friction;
  84728. };
  84729. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84730. return impostor.physicsBody.material.restitution;
  84731. };
  84732. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84733. impostor.physicsBody.material.restitution = restitution;
  84734. };
  84735. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84736. impostor.physicsBody.sleep();
  84737. };
  84738. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84739. impostor.physicsBody.wakeUp();
  84740. };
  84741. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84742. joint.physicsJoint.distance = maxDistance;
  84743. };
  84744. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84745. // if (!motorIndex) {
  84746. // joint.physicsJoint.enableMotor();
  84747. // }
  84748. // }
  84749. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84750. // if (!motorIndex) {
  84751. // joint.physicsJoint.disableMotor();
  84752. // }
  84753. // }
  84754. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84755. if (!motorIndex) {
  84756. joint.physicsJoint.enableMotor();
  84757. joint.physicsJoint.setMotorSpeed(speed);
  84758. if (maxForce) {
  84759. this.setLimit(joint, maxForce);
  84760. }
  84761. }
  84762. };
  84763. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84764. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84765. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84766. };
  84767. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84768. var body = impostor.physicsBody;
  84769. mesh.position.x = body.position.x;
  84770. mesh.position.y = body.position.y;
  84771. mesh.position.z = body.position.z;
  84772. if (mesh.rotationQuaternion) {
  84773. mesh.rotationQuaternion.x = body.quaternion.x;
  84774. mesh.rotationQuaternion.y = body.quaternion.y;
  84775. mesh.rotationQuaternion.z = body.quaternion.z;
  84776. mesh.rotationQuaternion.w = body.quaternion.w;
  84777. }
  84778. };
  84779. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84780. var shape = impostor.physicsBody.shapes[0];
  84781. return shape.boundingSphereRadius;
  84782. };
  84783. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84784. var shape = impostor.physicsBody.shapes[0];
  84785. result.x = shape.halfExtents.x * 2;
  84786. result.y = shape.halfExtents.y * 2;
  84787. result.z = shape.halfExtents.z * 2;
  84788. };
  84789. CannonJSPlugin.prototype.dispose = function () {
  84790. };
  84791. CannonJSPlugin.prototype._extendNamespace = function () {
  84792. //this will force cannon to execute at least one step when using interpolation
  84793. var step_tmp1 = new this.BJSCANNON.Vec3();
  84794. var Engine = this.BJSCANNON;
  84795. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84796. maxSubSteps = maxSubSteps || 10;
  84797. timeSinceLastCalled = timeSinceLastCalled || 0;
  84798. if (timeSinceLastCalled === 0) {
  84799. this.internalStep(dt);
  84800. this.time += dt;
  84801. }
  84802. else {
  84803. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84804. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84805. var t0 = performance.now();
  84806. for (var i = 0; i !== internalSteps; i++) {
  84807. this.internalStep(dt);
  84808. if (performance.now() - t0 > dt * 1000) {
  84809. break;
  84810. }
  84811. }
  84812. this.time += timeSinceLastCalled;
  84813. var h = this.time % dt;
  84814. var h_div_dt = h / dt;
  84815. var interpvelo = step_tmp1;
  84816. var bodies = this.bodies;
  84817. for (var j = 0; j !== bodies.length; j++) {
  84818. var b = bodies[j];
  84819. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84820. b.position.vsub(b.previousPosition, interpvelo);
  84821. interpvelo.scale(h_div_dt, interpvelo);
  84822. b.position.vadd(interpvelo, b.interpolatedPosition);
  84823. }
  84824. else {
  84825. b.interpolatedPosition.copy(b.position);
  84826. b.interpolatedQuaternion.copy(b.quaternion);
  84827. }
  84828. }
  84829. }
  84830. };
  84831. };
  84832. return CannonJSPlugin;
  84833. }());
  84834. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84835. })(BABYLON || (BABYLON = {}));
  84836. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84837. var BABYLON;
  84838. (function (BABYLON) {
  84839. var OimoJSPlugin = /** @class */ (function () {
  84840. function OimoJSPlugin(iterations) {
  84841. this.name = "OimoJSPlugin";
  84842. this._tmpImpostorsArray = [];
  84843. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84844. this.BJSOIMO = OIMO;
  84845. this.world = new this.BJSOIMO.World({
  84846. iterations: iterations
  84847. });
  84848. this.world.clear();
  84849. }
  84850. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84851. this.world.gravity.copy(gravity);
  84852. };
  84853. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84854. this.world.timeStep = timeStep;
  84855. };
  84856. OimoJSPlugin.prototype.getTimeStep = function () {
  84857. return this.world.timeStep;
  84858. };
  84859. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84860. var _this = this;
  84861. impostors.forEach(function (impostor) {
  84862. impostor.beforeStep();
  84863. });
  84864. this.world.step();
  84865. impostors.forEach(function (impostor) {
  84866. impostor.afterStep();
  84867. //update the ordered impostors array
  84868. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84869. });
  84870. //check for collisions
  84871. var contact = this.world.contacts;
  84872. while (contact !== null) {
  84873. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84874. contact = contact.next;
  84875. continue;
  84876. }
  84877. //is this body colliding with any other? get the impostor
  84878. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84879. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84880. if (!mainImpostor || !collidingImpostor) {
  84881. contact = contact.next;
  84882. continue;
  84883. }
  84884. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84885. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84886. contact = contact.next;
  84887. }
  84888. };
  84889. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84890. var mass = impostor.physicsBody.mass;
  84891. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84892. };
  84893. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84894. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84895. this.applyImpulse(impostor, force, contactPoint);
  84896. };
  84897. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84898. var _this = this;
  84899. //parent-child relationship. Does this impostor has a parent impostor?
  84900. if (impostor.parent) {
  84901. if (impostor.physicsBody) {
  84902. this.removePhysicsBody(impostor);
  84903. //TODO is that needed?
  84904. impostor.forceUpdate();
  84905. }
  84906. return;
  84907. }
  84908. if (impostor.isBodyInitRequired()) {
  84909. var bodyConfig = {
  84910. name: impostor.uniqueId,
  84911. //Oimo must have mass, also for static objects.
  84912. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84913. size: [],
  84914. type: [],
  84915. pos: [],
  84916. posShape: [],
  84917. rot: [],
  84918. rotShape: [],
  84919. move: impostor.getParam("mass") !== 0,
  84920. density: impostor.getParam("mass"),
  84921. friction: impostor.getParam("friction"),
  84922. restitution: impostor.getParam("restitution"),
  84923. //Supporting older versions of Oimo
  84924. world: this.world
  84925. };
  84926. var impostors = [impostor];
  84927. var addToArray = function (parent) {
  84928. if (!parent.getChildMeshes)
  84929. return;
  84930. parent.getChildMeshes().forEach(function (m) {
  84931. if (m.physicsImpostor) {
  84932. impostors.push(m.physicsImpostor);
  84933. //m.physicsImpostor._init();
  84934. }
  84935. });
  84936. };
  84937. addToArray(impostor.object);
  84938. var checkWithEpsilon_1 = function (value) {
  84939. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84940. };
  84941. impostors.forEach(function (i) {
  84942. if (!i.object.rotationQuaternion) {
  84943. return;
  84944. }
  84945. //get the correct bounding box
  84946. var oldQuaternion = i.object.rotationQuaternion;
  84947. var rot = oldQuaternion.toEulerAngles();
  84948. var extendSize = i.getObjectExtendSize();
  84949. var radToDeg = 57.295779513082320876;
  84950. if (i === impostor) {
  84951. var center = impostor.getObjectCenter();
  84952. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84953. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84954. //Can also use Array.prototype.push.apply
  84955. bodyConfig.pos.push(center.x);
  84956. bodyConfig.pos.push(center.y);
  84957. bodyConfig.pos.push(center.z);
  84958. bodyConfig.posShape.push(0, 0, 0);
  84959. //tmp solution
  84960. bodyConfig.rot.push(rot.x * radToDeg);
  84961. bodyConfig.rot.push(rot.y * radToDeg);
  84962. bodyConfig.rot.push(rot.z * radToDeg);
  84963. bodyConfig.rotShape.push(0, 0, 0);
  84964. }
  84965. else {
  84966. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84967. bodyConfig.posShape.push(localPosition.x);
  84968. bodyConfig.posShape.push(localPosition.y);
  84969. bodyConfig.posShape.push(localPosition.z);
  84970. bodyConfig.pos.push(0, 0, 0);
  84971. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84972. bodyConfig.rot.push(0);
  84973. bodyConfig.rot.push(0);
  84974. bodyConfig.rot.push(0);
  84975. bodyConfig.rotShape.push(rot.x * radToDeg);
  84976. bodyConfig.rotShape.push(rot.y * radToDeg);
  84977. bodyConfig.rotShape.push(rot.z * radToDeg);
  84978. }
  84979. // register mesh
  84980. switch (i.type) {
  84981. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84982. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84983. case BABYLON.PhysicsImpostor.SphereImpostor:
  84984. var radiusX = extendSize.x;
  84985. var radiusY = extendSize.y;
  84986. var radiusZ = extendSize.z;
  84987. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84988. bodyConfig.type.push('sphere');
  84989. //due to the way oimo works with compounds, add 3 times
  84990. bodyConfig.size.push(size);
  84991. bodyConfig.size.push(size);
  84992. bodyConfig.size.push(size);
  84993. break;
  84994. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84995. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84996. var sizeY = checkWithEpsilon_1(extendSize.y);
  84997. bodyConfig.type.push('cylinder');
  84998. bodyConfig.size.push(sizeX);
  84999. bodyConfig.size.push(sizeY);
  85000. //due to the way oimo works with compounds, add one more value.
  85001. bodyConfig.size.push(sizeY);
  85002. break;
  85003. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85004. case BABYLON.PhysicsImpostor.BoxImpostor:
  85005. default:
  85006. var sizeX = checkWithEpsilon_1(extendSize.x);
  85007. var sizeY = checkWithEpsilon_1(extendSize.y);
  85008. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85009. bodyConfig.type.push('box');
  85010. //if (i === impostor) {
  85011. bodyConfig.size.push(sizeX);
  85012. bodyConfig.size.push(sizeY);
  85013. bodyConfig.size.push(sizeZ);
  85014. //} else {
  85015. // bodyConfig.size.push(0,0,0);
  85016. //}
  85017. break;
  85018. }
  85019. //actually not needed, but hey...
  85020. i.object.rotationQuaternion = oldQuaternion;
  85021. });
  85022. impostor.physicsBody = this.world.add(bodyConfig);
  85023. }
  85024. else {
  85025. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85026. }
  85027. impostor.setDeltaPosition(this._tmpPositionVector);
  85028. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85029. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85030. };
  85031. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85032. //impostor.physicsBody.dispose();
  85033. //Same as : (older oimo versions)
  85034. this.world.removeRigidBody(impostor.physicsBody);
  85035. };
  85036. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85037. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85038. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85039. if (!mainBody || !connectedBody) {
  85040. return;
  85041. }
  85042. var jointData = impostorJoint.joint.jointData;
  85043. var options = jointData.nativeParams || {};
  85044. var type;
  85045. var nativeJointData = {
  85046. body1: mainBody,
  85047. body2: connectedBody,
  85048. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85049. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85050. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85051. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85052. min: options.min,
  85053. max: options.max,
  85054. collision: options.collision || jointData.collision,
  85055. spring: options.spring,
  85056. //supporting older version of Oimo
  85057. world: this.world
  85058. };
  85059. switch (impostorJoint.joint.type) {
  85060. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85061. type = "jointBall";
  85062. break;
  85063. case BABYLON.PhysicsJoint.SpringJoint:
  85064. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85065. var springData = jointData;
  85066. nativeJointData.min = springData.length || nativeJointData.min;
  85067. //Max should also be set, just make sure it is at least min
  85068. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85069. case BABYLON.PhysicsJoint.DistanceJoint:
  85070. type = "jointDistance";
  85071. nativeJointData.max = jointData.maxDistance;
  85072. break;
  85073. case BABYLON.PhysicsJoint.PrismaticJoint:
  85074. type = "jointPrisme";
  85075. break;
  85076. case BABYLON.PhysicsJoint.SliderJoint:
  85077. type = "jointSlide";
  85078. break;
  85079. case BABYLON.PhysicsJoint.WheelJoint:
  85080. type = "jointWheel";
  85081. break;
  85082. case BABYLON.PhysicsJoint.HingeJoint:
  85083. default:
  85084. type = "jointHinge";
  85085. break;
  85086. }
  85087. nativeJointData.type = type;
  85088. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85089. };
  85090. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85091. //Bug in Oimo prevents us from disposing a joint in the playground
  85092. //joint.joint.physicsJoint.dispose();
  85093. //So we will bruteforce it!
  85094. try {
  85095. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85096. }
  85097. catch (e) {
  85098. BABYLON.Tools.Warn(e);
  85099. }
  85100. };
  85101. OimoJSPlugin.prototype.isSupported = function () {
  85102. return this.BJSOIMO !== undefined;
  85103. };
  85104. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85105. if (!impostor.physicsBody.sleeping) {
  85106. //TODO check that
  85107. /*if (impostor.physicsBody.shapes.next) {
  85108. var parentShape = this._getLastShape(impostor.physicsBody);
  85109. impostor.object.position.copyFrom(parentShape.position);
  85110. console.log(parentShape.position);
  85111. } else {*/
  85112. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85113. //}
  85114. if (impostor.object.rotationQuaternion) {
  85115. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85116. }
  85117. }
  85118. };
  85119. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85120. var body = impostor.physicsBody;
  85121. body.position.copy(newPosition);
  85122. body.orientation.copy(newRotation);
  85123. body.syncShapes();
  85124. body.awake();
  85125. };
  85126. /*private _getLastShape(body: any): any {
  85127. var lastShape = body.shapes;
  85128. while (lastShape.next) {
  85129. lastShape = lastShape.next;
  85130. }
  85131. return lastShape;
  85132. }*/
  85133. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85134. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  85135. };
  85136. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85137. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  85138. };
  85139. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85140. var v = impostor.physicsBody.linearVelocity;
  85141. if (!v) {
  85142. return null;
  85143. }
  85144. return new BABYLON.Vector3(v.x, v.y, v.z);
  85145. };
  85146. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85147. var v = impostor.physicsBody.angularVelocity;
  85148. if (!v) {
  85149. return null;
  85150. }
  85151. return new BABYLON.Vector3(v.x, v.y, v.z);
  85152. };
  85153. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85154. var staticBody = mass === 0;
  85155. //this will actually set the body's density and not its mass.
  85156. //But this is how oimo treats the mass variable.
  85157. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  85158. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  85159. };
  85160. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  85161. return impostor.physicsBody.shapes.density;
  85162. };
  85163. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  85164. return impostor.physicsBody.shapes.friction;
  85165. };
  85166. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85167. impostor.physicsBody.shapes.friction = friction;
  85168. };
  85169. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85170. return impostor.physicsBody.shapes.restitution;
  85171. };
  85172. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85173. impostor.physicsBody.shapes.restitution = restitution;
  85174. };
  85175. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  85176. impostor.physicsBody.sleep();
  85177. };
  85178. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  85179. impostor.physicsBody.awake();
  85180. };
  85181. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85182. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  85183. if (minDistance !== void 0) {
  85184. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  85185. }
  85186. };
  85187. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85188. //TODO separate rotational and transational motors.
  85189. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85190. if (motor) {
  85191. motor.setMotor(speed, maxForce);
  85192. }
  85193. };
  85194. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  85195. //TODO separate rotational and transational motors.
  85196. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  85197. if (motor) {
  85198. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  85199. }
  85200. };
  85201. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85202. var body = impostor.physicsBody;
  85203. mesh.position.x = body.position.x;
  85204. mesh.position.y = body.position.y;
  85205. mesh.position.z = body.position.z;
  85206. if (mesh.rotationQuaternion) {
  85207. mesh.rotationQuaternion.x = body.orientation.x;
  85208. mesh.rotationQuaternion.y = body.orientation.y;
  85209. mesh.rotationQuaternion.z = body.orientation.z;
  85210. mesh.rotationQuaternion.w = body.orientation.s;
  85211. }
  85212. };
  85213. OimoJSPlugin.prototype.getRadius = function (impostor) {
  85214. return impostor.physicsBody.shapes.radius;
  85215. };
  85216. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85217. var shape = impostor.physicsBody.shapes;
  85218. result.x = shape.halfWidth * 2;
  85219. result.y = shape.halfHeight * 2;
  85220. result.z = shape.halfDepth * 2;
  85221. };
  85222. OimoJSPlugin.prototype.dispose = function () {
  85223. this.world.clear();
  85224. };
  85225. return OimoJSPlugin;
  85226. }());
  85227. BABYLON.OimoJSPlugin = OimoJSPlugin;
  85228. })(BABYLON || (BABYLON = {}));
  85229. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  85230. var BABYLON;
  85231. (function (BABYLON) {
  85232. /*
  85233. * Based on jsTGALoader - Javascript loader for TGA file
  85234. * By Vincent Thibault
  85235. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  85236. */
  85237. var TGATools = /** @class */ (function () {
  85238. function TGATools() {
  85239. }
  85240. TGATools.GetTGAHeader = function (data) {
  85241. var offset = 0;
  85242. var header = {
  85243. id_length: data[offset++],
  85244. colormap_type: data[offset++],
  85245. image_type: data[offset++],
  85246. colormap_index: data[offset++] | data[offset++] << 8,
  85247. colormap_length: data[offset++] | data[offset++] << 8,
  85248. colormap_size: data[offset++],
  85249. origin: [
  85250. data[offset++] | data[offset++] << 8,
  85251. data[offset++] | data[offset++] << 8
  85252. ],
  85253. width: data[offset++] | data[offset++] << 8,
  85254. height: data[offset++] | data[offset++] << 8,
  85255. pixel_size: data[offset++],
  85256. flags: data[offset++]
  85257. };
  85258. return header;
  85259. };
  85260. TGATools.UploadContent = function (gl, data) {
  85261. // Not enough data to contain header ?
  85262. if (data.length < 19) {
  85263. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  85264. return;
  85265. }
  85266. // Read Header
  85267. var offset = 18;
  85268. var header = TGATools.GetTGAHeader(data);
  85269. // Assume it's a valid Targa file.
  85270. if (header.id_length + offset > data.length) {
  85271. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  85272. return;
  85273. }
  85274. // Skip not needed data
  85275. offset += header.id_length;
  85276. var use_rle = false;
  85277. var use_pal = false;
  85278. var use_grey = false;
  85279. // Get some informations.
  85280. switch (header.image_type) {
  85281. case TGATools._TYPE_RLE_INDEXED:
  85282. use_rle = true;
  85283. case TGATools._TYPE_INDEXED:
  85284. use_pal = true;
  85285. break;
  85286. case TGATools._TYPE_RLE_RGB:
  85287. use_rle = true;
  85288. case TGATools._TYPE_RGB:
  85289. // use_rgb = true;
  85290. break;
  85291. case TGATools._TYPE_RLE_GREY:
  85292. use_rle = true;
  85293. case TGATools._TYPE_GREY:
  85294. use_grey = true;
  85295. break;
  85296. }
  85297. var pixel_data;
  85298. // var numAlphaBits = header.flags & 0xf;
  85299. var pixel_size = header.pixel_size >> 3;
  85300. var pixel_total = header.width * header.height * pixel_size;
  85301. // Read palettes
  85302. var palettes;
  85303. if (use_pal) {
  85304. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  85305. }
  85306. // Read LRE
  85307. if (use_rle) {
  85308. pixel_data = new Uint8Array(pixel_total);
  85309. var c, count, i;
  85310. var localOffset = 0;
  85311. var pixels = new Uint8Array(pixel_size);
  85312. while (offset < pixel_total && localOffset < pixel_total) {
  85313. c = data[offset++];
  85314. count = (c & 0x7f) + 1;
  85315. // RLE pixels
  85316. if (c & 0x80) {
  85317. // Bind pixel tmp array
  85318. for (i = 0; i < pixel_size; ++i) {
  85319. pixels[i] = data[offset++];
  85320. }
  85321. // Copy pixel array
  85322. for (i = 0; i < count; ++i) {
  85323. pixel_data.set(pixels, localOffset + i * pixel_size);
  85324. }
  85325. localOffset += pixel_size * count;
  85326. }
  85327. // Raw pixels
  85328. else {
  85329. count *= pixel_size;
  85330. for (i = 0; i < count; ++i) {
  85331. pixel_data[localOffset + i] = data[offset++];
  85332. }
  85333. localOffset += count;
  85334. }
  85335. }
  85336. }
  85337. // RAW Pixels
  85338. else {
  85339. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  85340. }
  85341. // Load to texture
  85342. var x_start, y_start, x_step, y_step, y_end, x_end;
  85343. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  85344. default:
  85345. case TGATools._ORIGIN_UL:
  85346. x_start = 0;
  85347. x_step = 1;
  85348. x_end = header.width;
  85349. y_start = 0;
  85350. y_step = 1;
  85351. y_end = header.height;
  85352. break;
  85353. case TGATools._ORIGIN_BL:
  85354. x_start = 0;
  85355. x_step = 1;
  85356. x_end = header.width;
  85357. y_start = header.height - 1;
  85358. y_step = -1;
  85359. y_end = -1;
  85360. break;
  85361. case TGATools._ORIGIN_UR:
  85362. x_start = header.width - 1;
  85363. x_step = -1;
  85364. x_end = -1;
  85365. y_start = 0;
  85366. y_step = 1;
  85367. y_end = header.height;
  85368. break;
  85369. case TGATools._ORIGIN_BR:
  85370. x_start = header.width - 1;
  85371. x_step = -1;
  85372. x_end = -1;
  85373. y_start = header.height - 1;
  85374. y_step = -1;
  85375. y_end = -1;
  85376. break;
  85377. }
  85378. // Load the specify method
  85379. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  85380. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  85381. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  85382. };
  85383. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85384. var image = pixel_data, colormap = palettes;
  85385. var width = header.width, height = header.height;
  85386. var color, i = 0, x, y;
  85387. var imageData = new Uint8Array(width * height * 4);
  85388. for (y = y_start; y !== y_end; y += y_step) {
  85389. for (x = x_start; x !== x_end; x += x_step, i++) {
  85390. color = image[i];
  85391. imageData[(x + width * y) * 4 + 3] = 255;
  85392. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  85393. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  85394. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  85395. }
  85396. }
  85397. return imageData;
  85398. };
  85399. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85400. var image = pixel_data;
  85401. var width = header.width, height = header.height;
  85402. var color, i = 0, x, y;
  85403. var imageData = new Uint8Array(width * height * 4);
  85404. for (y = y_start; y !== y_end; y += y_step) {
  85405. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85406. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  85407. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  85408. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  85409. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  85410. imageData[(x + width * y) * 4 + 0] = r;
  85411. imageData[(x + width * y) * 4 + 1] = g;
  85412. imageData[(x + width * y) * 4 + 2] = b;
  85413. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  85414. }
  85415. }
  85416. return imageData;
  85417. };
  85418. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85419. var image = pixel_data;
  85420. var width = header.width, height = header.height;
  85421. var i = 0, x, y;
  85422. var imageData = new Uint8Array(width * height * 4);
  85423. for (y = y_start; y !== y_end; y += y_step) {
  85424. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  85425. imageData[(x + width * y) * 4 + 3] = 255;
  85426. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85427. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85428. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85429. }
  85430. }
  85431. return imageData;
  85432. };
  85433. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85434. var image = pixel_data;
  85435. var width = header.width, height = header.height;
  85436. var i = 0, x, y;
  85437. var imageData = new Uint8Array(width * height * 4);
  85438. for (y = y_start; y !== y_end; y += y_step) {
  85439. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  85440. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85441. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  85442. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  85443. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  85444. }
  85445. }
  85446. return imageData;
  85447. };
  85448. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85449. var image = pixel_data;
  85450. var width = header.width, height = header.height;
  85451. var color, i = 0, x, y;
  85452. var imageData = new Uint8Array(width * height * 4);
  85453. for (y = y_start; y !== y_end; y += y_step) {
  85454. for (x = x_start; x !== x_end; x += x_step, i++) {
  85455. color = image[i];
  85456. imageData[(x + width * y) * 4 + 0] = color;
  85457. imageData[(x + width * y) * 4 + 1] = color;
  85458. imageData[(x + width * y) * 4 + 2] = color;
  85459. imageData[(x + width * y) * 4 + 3] = 255;
  85460. }
  85461. }
  85462. return imageData;
  85463. };
  85464. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  85465. var image = pixel_data;
  85466. var width = header.width, height = header.height;
  85467. var i = 0, x, y;
  85468. var imageData = new Uint8Array(width * height * 4);
  85469. for (y = y_start; y !== y_end; y += y_step) {
  85470. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  85471. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  85472. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  85473. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  85474. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  85475. }
  85476. }
  85477. return imageData;
  85478. };
  85479. //private static _TYPE_NO_DATA = 0;
  85480. TGATools._TYPE_INDEXED = 1;
  85481. TGATools._TYPE_RGB = 2;
  85482. TGATools._TYPE_GREY = 3;
  85483. TGATools._TYPE_RLE_INDEXED = 9;
  85484. TGATools._TYPE_RLE_RGB = 10;
  85485. TGATools._TYPE_RLE_GREY = 11;
  85486. TGATools._ORIGIN_MASK = 0x30;
  85487. TGATools._ORIGIN_SHIFT = 0x04;
  85488. TGATools._ORIGIN_BL = 0x00;
  85489. TGATools._ORIGIN_BR = 0x01;
  85490. TGATools._ORIGIN_UL = 0x02;
  85491. TGATools._ORIGIN_UR = 0x03;
  85492. return TGATools;
  85493. }());
  85494. BABYLON.TGATools = TGATools;
  85495. })(BABYLON || (BABYLON = {}));
  85496. //# sourceMappingURL=babylon.tga.js.map
  85497. var BABYLON;
  85498. (function (BABYLON) {
  85499. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  85500. // All values and structures referenced from:
  85501. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  85502. var DDS_MAGIC = 0x20534444;
  85503. var
  85504. //DDSD_CAPS = 0x1,
  85505. //DDSD_HEIGHT = 0x2,
  85506. //DDSD_WIDTH = 0x4,
  85507. //DDSD_PITCH = 0x8,
  85508. //DDSD_PIXELFORMAT = 0x1000,
  85509. DDSD_MIPMAPCOUNT = 0x20000;
  85510. //DDSD_LINEARSIZE = 0x80000,
  85511. //DDSD_DEPTH = 0x800000;
  85512. // var DDSCAPS_COMPLEX = 0x8,
  85513. // DDSCAPS_MIPMAP = 0x400000,
  85514. // DDSCAPS_TEXTURE = 0x1000;
  85515. var DDSCAPS2_CUBEMAP = 0x200;
  85516. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  85517. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  85518. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  85519. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  85520. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  85521. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  85522. // DDSCAPS2_VOLUME = 0x200000;
  85523. var
  85524. //DDPF_ALPHAPIXELS = 0x1,
  85525. //DDPF_ALPHA = 0x2,
  85526. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  85527. //DDPF_YUV = 0x200,
  85528. DDPF_LUMINANCE = 0x20000;
  85529. function FourCCToInt32(value) {
  85530. return value.charCodeAt(0) +
  85531. (value.charCodeAt(1) << 8) +
  85532. (value.charCodeAt(2) << 16) +
  85533. (value.charCodeAt(3) << 24);
  85534. }
  85535. function Int32ToFourCC(value) {
  85536. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  85537. }
  85538. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  85539. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  85540. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  85541. var FOURCC_DX10 = FourCCToInt32("DX10");
  85542. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  85543. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  85544. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  85545. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  85546. var headerLengthInt = 31; // The header length in 32 bit ints
  85547. // Offsets into the header array
  85548. var off_magic = 0;
  85549. var off_size = 1;
  85550. var off_flags = 2;
  85551. var off_height = 3;
  85552. var off_width = 4;
  85553. var off_mipmapCount = 7;
  85554. var off_pfFlags = 20;
  85555. var off_pfFourCC = 21;
  85556. var off_RGBbpp = 22;
  85557. var off_RMask = 23;
  85558. var off_GMask = 24;
  85559. var off_BMask = 25;
  85560. var off_AMask = 26;
  85561. // var off_caps1 = 27;
  85562. var off_caps2 = 28;
  85563. // var off_caps3 = 29;
  85564. // var off_caps4 = 30;
  85565. var off_dxgiFormat = 32;
  85566. ;
  85567. var DDSTools = /** @class */ (function () {
  85568. function DDSTools() {
  85569. }
  85570. DDSTools.GetDDSInfo = function (arrayBuffer) {
  85571. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85572. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  85573. var mipmapCount = 1;
  85574. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  85575. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85576. }
  85577. var fourCC = header[off_pfFourCC];
  85578. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  85579. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85580. switch (fourCC) {
  85581. case FOURCC_D3DFMT_R16G16B16A16F:
  85582. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85583. break;
  85584. case FOURCC_D3DFMT_R32G32B32A32F:
  85585. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85586. break;
  85587. case FOURCC_DX10:
  85588. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85589. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85590. break;
  85591. }
  85592. }
  85593. return {
  85594. width: header[off_width],
  85595. height: header[off_height],
  85596. mipmapCount: mipmapCount,
  85597. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85598. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85599. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85600. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85601. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85602. dxgiFormat: dxgiFormat,
  85603. textureType: textureType
  85604. };
  85605. };
  85606. DDSTools._ToHalfFloat = function (value) {
  85607. if (!DDSTools._FloatView) {
  85608. DDSTools._FloatView = new Float32Array(1);
  85609. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85610. }
  85611. DDSTools._FloatView[0] = value;
  85612. var x = DDSTools._Int32View[0];
  85613. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85614. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85615. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85616. /* If zero, or denormal, or exponent underflows too much for a denormal
  85617. * half, return signed zero. */
  85618. if (e < 103) {
  85619. return bits;
  85620. }
  85621. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85622. if (e > 142) {
  85623. bits |= 0x7c00;
  85624. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85625. * not Inf, so make sure we set one mantissa bit too. */
  85626. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85627. return bits;
  85628. }
  85629. /* If exponent underflows but not too much, return a denormal */
  85630. if (e < 113) {
  85631. m |= 0x0800;
  85632. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85633. * to 1, which is OK. */
  85634. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85635. return bits;
  85636. }
  85637. bits |= ((e - 112) << 10) | (m >> 1);
  85638. bits += m & 1;
  85639. return bits;
  85640. };
  85641. DDSTools._FromHalfFloat = function (value) {
  85642. var s = (value & 0x8000) >> 15;
  85643. var e = (value & 0x7C00) >> 10;
  85644. var f = value & 0x03FF;
  85645. if (e === 0) {
  85646. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85647. }
  85648. else if (e == 0x1F) {
  85649. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85650. }
  85651. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85652. };
  85653. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85654. var destArray = new Float32Array(dataLength);
  85655. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85656. var index = 0;
  85657. for (var y = 0; y < height; y++) {
  85658. for (var x = 0; x < width; x++) {
  85659. var srcPos = (x + y * width) * 4;
  85660. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85661. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85662. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85663. if (DDSTools.StoreLODInAlphaChannel) {
  85664. destArray[index + 3] = lod;
  85665. }
  85666. else {
  85667. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85668. }
  85669. index += 4;
  85670. }
  85671. }
  85672. return destArray;
  85673. };
  85674. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85675. if (DDSTools.StoreLODInAlphaChannel) {
  85676. var destArray = new Uint16Array(dataLength);
  85677. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85678. var index = 0;
  85679. for (var y = 0; y < height; y++) {
  85680. for (var x = 0; x < width; x++) {
  85681. var srcPos = (x + y * width) * 4;
  85682. destArray[index] = srcData[srcPos];
  85683. destArray[index + 1] = srcData[srcPos + 1];
  85684. destArray[index + 2] = srcData[srcPos + 2];
  85685. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85686. index += 4;
  85687. }
  85688. }
  85689. return destArray;
  85690. }
  85691. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85692. };
  85693. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85694. if (DDSTools.StoreLODInAlphaChannel) {
  85695. var destArray = new Float32Array(dataLength);
  85696. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85697. var index = 0;
  85698. for (var y = 0; y < height; y++) {
  85699. for (var x = 0; x < width; x++) {
  85700. var srcPos = (x + y * width) * 4;
  85701. destArray[index] = srcData[srcPos];
  85702. destArray[index + 1] = srcData[srcPos + 1];
  85703. destArray[index + 2] = srcData[srcPos + 2];
  85704. destArray[index + 3] = lod;
  85705. index += 4;
  85706. }
  85707. }
  85708. return destArray;
  85709. }
  85710. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85711. };
  85712. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85713. var destArray = new Uint8Array(dataLength);
  85714. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85715. var index = 0;
  85716. for (var y = 0; y < height; y++) {
  85717. for (var x = 0; x < width; x++) {
  85718. var srcPos = (x + y * width) * 4;
  85719. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85720. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85721. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85722. if (DDSTools.StoreLODInAlphaChannel) {
  85723. destArray[index + 3] = lod;
  85724. }
  85725. else {
  85726. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85727. }
  85728. index += 4;
  85729. }
  85730. }
  85731. return destArray;
  85732. };
  85733. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85734. var destArray = new Uint8Array(dataLength);
  85735. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85736. var index = 0;
  85737. for (var y = 0; y < height; y++) {
  85738. for (var x = 0; x < width; x++) {
  85739. var srcPos = (x + y * width) * 4;
  85740. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85741. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85742. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85743. if (DDSTools.StoreLODInAlphaChannel) {
  85744. destArray[index + 3] = lod;
  85745. }
  85746. else {
  85747. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85748. }
  85749. index += 4;
  85750. }
  85751. }
  85752. return destArray;
  85753. };
  85754. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85755. var byteArray = new Uint8Array(dataLength);
  85756. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85757. var index = 0;
  85758. for (var y = 0; y < height; y++) {
  85759. for (var x = 0; x < width; x++) {
  85760. var srcPos = (x + y * width) * 4;
  85761. byteArray[index] = srcData[srcPos + rOffset];
  85762. byteArray[index + 1] = srcData[srcPos + gOffset];
  85763. byteArray[index + 2] = srcData[srcPos + bOffset];
  85764. byteArray[index + 3] = srcData[srcPos + aOffset];
  85765. index += 4;
  85766. }
  85767. }
  85768. return byteArray;
  85769. };
  85770. DDSTools._ExtractLongWordOrder = function (value) {
  85771. if (value === 0 || value === 255 || value === -16777216) {
  85772. return 0;
  85773. }
  85774. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85775. };
  85776. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85777. var byteArray = new Uint8Array(dataLength);
  85778. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85779. var index = 0;
  85780. for (var y = 0; y < height; y++) {
  85781. for (var x = 0; x < width; x++) {
  85782. var srcPos = (x + y * width) * 3;
  85783. byteArray[index] = srcData[srcPos + rOffset];
  85784. byteArray[index + 1] = srcData[srcPos + gOffset];
  85785. byteArray[index + 2] = srcData[srcPos + bOffset];
  85786. index += 3;
  85787. }
  85788. }
  85789. return byteArray;
  85790. };
  85791. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85792. var byteArray = new Uint8Array(dataLength);
  85793. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85794. var index = 0;
  85795. for (var y = 0; y < height; y++) {
  85796. for (var x = 0; x < width; x++) {
  85797. var srcPos = (x + y * width);
  85798. byteArray[index] = srcData[srcPos];
  85799. index++;
  85800. }
  85801. }
  85802. return byteArray;
  85803. };
  85804. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85805. if (lodIndex === void 0) { lodIndex = -1; }
  85806. var sphericalPolynomialFaces = null;
  85807. if (info.sphericalPolynomial) {
  85808. sphericalPolynomialFaces = new Array();
  85809. }
  85810. var ext = engine.getCaps().s3tc;
  85811. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85812. var fourCC, width, height, dataLength = 0, dataOffset;
  85813. var byteArray, mipmapCount, mip;
  85814. var internalFormat = 0;
  85815. var format = 0;
  85816. var blockBytes = 1;
  85817. if (header[off_magic] !== DDS_MAGIC) {
  85818. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85819. return;
  85820. }
  85821. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85822. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85823. return;
  85824. }
  85825. if (info.isCompressed && !ext) {
  85826. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85827. return;
  85828. }
  85829. var bpp = header[off_RGBbpp];
  85830. dataOffset = header[off_size] + 4;
  85831. var computeFormats = false;
  85832. if (info.isFourCC) {
  85833. fourCC = header[off_pfFourCC];
  85834. switch (fourCC) {
  85835. case FOURCC_DXT1:
  85836. blockBytes = 8;
  85837. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85838. break;
  85839. case FOURCC_DXT3:
  85840. blockBytes = 16;
  85841. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85842. break;
  85843. case FOURCC_DXT5:
  85844. blockBytes = 16;
  85845. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85846. break;
  85847. case FOURCC_D3DFMT_R16G16B16A16F:
  85848. computeFormats = true;
  85849. break;
  85850. case FOURCC_D3DFMT_R32G32B32A32F:
  85851. computeFormats = true;
  85852. break;
  85853. case FOURCC_DX10:
  85854. // There is an additionnal header so dataOffset need to be changed
  85855. dataOffset += 5 * 4; // 5 uints
  85856. var supported = false;
  85857. switch (info.dxgiFormat) {
  85858. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85859. computeFormats = true;
  85860. supported = true;
  85861. break;
  85862. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85863. info.isRGB = true;
  85864. info.isFourCC = false;
  85865. bpp = 32;
  85866. supported = true;
  85867. break;
  85868. }
  85869. if (supported) {
  85870. break;
  85871. }
  85872. default:
  85873. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85874. return;
  85875. }
  85876. }
  85877. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85878. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85879. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85880. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85881. if (computeFormats) {
  85882. format = engine._getWebGLTextureType(info.textureType);
  85883. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85884. }
  85885. mipmapCount = 1;
  85886. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85887. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85888. }
  85889. for (var face = 0; face < faces; face++) {
  85890. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85891. width = header[off_width];
  85892. height = header[off_height];
  85893. for (mip = 0; mip < mipmapCount; ++mip) {
  85894. if (lodIndex === -1 || lodIndex === mip) {
  85895. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85896. var i = (lodIndex === -1) ? mip : 0;
  85897. if (!info.isCompressed && info.isFourCC) {
  85898. dataLength = width * height * 4;
  85899. var floatArray = null;
  85900. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85901. if (bpp === 128) {
  85902. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85903. if (sphericalPolynomialFaces && i == 0) {
  85904. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85905. }
  85906. }
  85907. else if (bpp === 64) {
  85908. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85909. if (sphericalPolynomialFaces && i == 0) {
  85910. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85911. }
  85912. }
  85913. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85914. format = engine._getWebGLTextureType(info.textureType);
  85915. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85916. }
  85917. else {
  85918. if (bpp === 128) {
  85919. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85920. if (sphericalPolynomialFaces && i == 0) {
  85921. sphericalPolynomialFaces.push(floatArray);
  85922. }
  85923. }
  85924. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85925. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85926. if (sphericalPolynomialFaces && i == 0) {
  85927. sphericalPolynomialFaces.push(floatArray);
  85928. }
  85929. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85930. format = engine._getWebGLTextureType(info.textureType);
  85931. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85932. }
  85933. else { // 64
  85934. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85935. if (sphericalPolynomialFaces && i == 0) {
  85936. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85937. }
  85938. }
  85939. }
  85940. if (floatArray) {
  85941. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85942. }
  85943. }
  85944. else if (info.isRGB) {
  85945. if (bpp === 24) {
  85946. dataLength = width * height * 3;
  85947. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85948. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85949. }
  85950. else { // 32
  85951. dataLength = width * height * 4;
  85952. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85953. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85954. }
  85955. }
  85956. else if (info.isLuminance) {
  85957. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85958. var unpaddedRowSize = width;
  85959. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85960. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85961. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85962. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85963. }
  85964. else {
  85965. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85966. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85967. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85968. }
  85969. }
  85970. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85971. width *= 0.5;
  85972. height *= 0.5;
  85973. width = Math.max(1.0, width);
  85974. height = Math.max(1.0, height);
  85975. }
  85976. if (currentFace !== undefined) {
  85977. // Loading a single face
  85978. break;
  85979. }
  85980. }
  85981. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85982. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85983. size: header[off_width],
  85984. right: sphericalPolynomialFaces[0],
  85985. left: sphericalPolynomialFaces[1],
  85986. up: sphericalPolynomialFaces[2],
  85987. down: sphericalPolynomialFaces[3],
  85988. front: sphericalPolynomialFaces[4],
  85989. back: sphericalPolynomialFaces[5],
  85990. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85991. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85992. gammaSpace: false,
  85993. });
  85994. }
  85995. else {
  85996. info.sphericalPolynomial = undefined;
  85997. }
  85998. };
  85999. DDSTools.StoreLODInAlphaChannel = false;
  86000. return DDSTools;
  86001. }());
  86002. BABYLON.DDSTools = DDSTools;
  86003. })(BABYLON || (BABYLON = {}));
  86004. //# sourceMappingURL=babylon.dds.js.map
  86005. var BABYLON;
  86006. (function (BABYLON) {
  86007. /**
  86008. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86009. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86010. */
  86011. var KhronosTextureContainer = /** @class */ (function () {
  86012. /**
  86013. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86014. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86015. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86016. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86017. */
  86018. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86019. this.arrayBuffer = arrayBuffer;
  86020. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86021. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86022. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86023. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86024. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86025. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86026. BABYLON.Tools.Error("texture missing KTX identifier");
  86027. return;
  86028. }
  86029. // load the reset of the header in native 32 bit int
  86030. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86031. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86032. var oppositeEndianess = header[0] === 0x01020304;
  86033. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86034. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86035. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86036. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86037. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86038. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86039. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86040. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86041. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86042. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86043. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86044. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86045. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86046. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86047. if (this.glType !== 0) {
  86048. BABYLON.Tools.Error("only compressed formats currently supported");
  86049. return;
  86050. }
  86051. else {
  86052. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86053. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86054. }
  86055. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86056. BABYLON.Tools.Error("only 2D textures currently supported");
  86057. return;
  86058. }
  86059. if (this.numberOfArrayElements !== 0) {
  86060. BABYLON.Tools.Error("texture arrays not currently supported");
  86061. return;
  86062. }
  86063. if (this.numberOfFaces !== facesExpected) {
  86064. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86065. return;
  86066. }
  86067. // we now have a completely validated file, so could use existence of loadType as success
  86068. // would need to make this more elaborate & adjust checks above to support more than one load type
  86069. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86070. }
  86071. // not as fast hardware based, but will probably never need to use
  86072. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86073. return ((val & 0xFF) << 24)
  86074. | ((val & 0xFF00) << 8)
  86075. | ((val >> 8) & 0xFF00)
  86076. | ((val >> 24) & 0xFF);
  86077. };
  86078. /**
  86079. * It is assumed that the texture has already been created & is currently bound
  86080. */
  86081. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86082. switch (this.loadType) {
  86083. case KhronosTextureContainer.COMPRESSED_2D:
  86084. this._upload2DCompressedLevels(gl, loadMipmaps);
  86085. break;
  86086. case KhronosTextureContainer.TEX_2D:
  86087. case KhronosTextureContainer.COMPRESSED_3D:
  86088. case KhronosTextureContainer.TEX_3D:
  86089. }
  86090. };
  86091. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86092. // initialize width & height for level 1
  86093. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86094. var width = this.pixelWidth;
  86095. var height = this.pixelHeight;
  86096. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86097. for (var level = 0; level < mipmapCount; level++) {
  86098. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86099. for (var face = 0; face < this.numberOfFaces; face++) {
  86100. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86101. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86102. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86103. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86104. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86105. }
  86106. width = Math.max(1.0, width * 0.5);
  86107. height = Math.max(1.0, height * 0.5);
  86108. }
  86109. };
  86110. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86111. // load types
  86112. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86113. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86114. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86115. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86116. return KhronosTextureContainer;
  86117. }());
  86118. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86119. })(BABYLON || (BABYLON = {}));
  86120. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86121. var BABYLON;
  86122. (function (BABYLON) {
  86123. var Debug;
  86124. (function (Debug) {
  86125. /**
  86126. * Class used to render a debug view of a given skeleton
  86127. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86128. */
  86129. var SkeletonViewer = /** @class */ (function () {
  86130. /**
  86131. * Creates a new SkeletonViewer
  86132. * @param skeleton defines the skeleton to render
  86133. * @param mesh defines the mesh attached to the skeleton
  86134. * @param scene defines the hosting scene
  86135. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  86136. * @param renderingGroupId defines the rendering group id to use with the viewer
  86137. */
  86138. function SkeletonViewer(
  86139. /** defines the skeleton to render */
  86140. skeleton,
  86141. /** defines the mesh attached to the skeleton */
  86142. mesh, scene,
  86143. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  86144. autoUpdateBonesMatrices,
  86145. /** defines the rendering group id to use with the viewer */
  86146. renderingGroupId) {
  86147. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  86148. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  86149. this.skeleton = skeleton;
  86150. this.mesh = mesh;
  86151. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  86152. this.renderingGroupId = renderingGroupId;
  86153. /** Gets or sets the color used to render the skeleton */
  86154. this.color = BABYLON.Color3.White();
  86155. this._debugLines = new Array();
  86156. this._isEnabled = false;
  86157. this._scene = scene;
  86158. this.update();
  86159. this._renderFunction = this.update.bind(this);
  86160. }
  86161. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  86162. get: function () {
  86163. return this._isEnabled;
  86164. },
  86165. /** Gets or sets a boolean indicating if the viewer is enabled */
  86166. set: function (value) {
  86167. if (this._isEnabled === value) {
  86168. return;
  86169. }
  86170. this._isEnabled = value;
  86171. if (value) {
  86172. this._scene.registerBeforeRender(this._renderFunction);
  86173. }
  86174. else {
  86175. this._scene.unregisterBeforeRender(this._renderFunction);
  86176. }
  86177. },
  86178. enumerable: true,
  86179. configurable: true
  86180. });
  86181. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  86182. if (x === void 0) { x = 0; }
  86183. if (y === void 0) { y = 0; }
  86184. if (z === void 0) { z = 0; }
  86185. var tmat = BABYLON.Tmp.Matrix[0];
  86186. var parentBone = bone.getParent();
  86187. tmat.copyFrom(bone.getLocalMatrix());
  86188. if (x !== 0 || y !== 0 || z !== 0) {
  86189. var tmat2 = BABYLON.Tmp.Matrix[1];
  86190. BABYLON.Matrix.IdentityToRef(tmat2);
  86191. tmat2.m[12] = x;
  86192. tmat2.m[13] = y;
  86193. tmat2.m[14] = z;
  86194. tmat2.multiplyToRef(tmat, tmat);
  86195. }
  86196. if (parentBone) {
  86197. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  86198. }
  86199. tmat.multiplyToRef(meshMat, tmat);
  86200. position.x = tmat.m[12];
  86201. position.y = tmat.m[13];
  86202. position.z = tmat.m[14];
  86203. };
  86204. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  86205. var len = bones.length;
  86206. var meshPos = this.mesh.position;
  86207. for (var i = 0; i < len; i++) {
  86208. var bone = bones[i];
  86209. var points = this._debugLines[i];
  86210. if (!points) {
  86211. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86212. this._debugLines[i] = points;
  86213. }
  86214. this._getBonePosition(points[0], bone, meshMat);
  86215. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  86216. points[0].subtractInPlace(meshPos);
  86217. points[1].subtractInPlace(meshPos);
  86218. }
  86219. };
  86220. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  86221. var len = bones.length;
  86222. var boneNum = 0;
  86223. var meshPos = this.mesh.position;
  86224. for (var i = len - 1; i >= 0; i--) {
  86225. var childBone = bones[i];
  86226. var parentBone = childBone.getParent();
  86227. if (!parentBone) {
  86228. continue;
  86229. }
  86230. var points = this._debugLines[boneNum];
  86231. if (!points) {
  86232. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86233. this._debugLines[boneNum] = points;
  86234. }
  86235. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  86236. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  86237. points[0].subtractInPlace(meshPos);
  86238. points[1].subtractInPlace(meshPos);
  86239. boneNum++;
  86240. }
  86241. };
  86242. /** Update the viewer to sync with current skeleton state */
  86243. SkeletonViewer.prototype.update = function () {
  86244. if (this.autoUpdateBonesMatrices) {
  86245. this.skeleton.computeAbsoluteTransforms();
  86246. }
  86247. if (this.skeleton.bones[0].length === undefined) {
  86248. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86249. }
  86250. else {
  86251. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  86252. }
  86253. if (!this._debugMesh) {
  86254. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  86255. this._debugMesh.renderingGroupId = this.renderingGroupId;
  86256. }
  86257. else {
  86258. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  86259. }
  86260. this._debugMesh.position.copyFrom(this.mesh.position);
  86261. this._debugMesh.color = this.color;
  86262. };
  86263. /** Release associated resources */
  86264. SkeletonViewer.prototype.dispose = function () {
  86265. if (this._debugMesh) {
  86266. this.isEnabled = false;
  86267. this._debugMesh.dispose();
  86268. this._debugMesh = null;
  86269. }
  86270. };
  86271. return SkeletonViewer;
  86272. }());
  86273. Debug.SkeletonViewer = SkeletonViewer;
  86274. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86275. })(BABYLON || (BABYLON = {}));
  86276. //# sourceMappingURL=babylon.skeletonViewer.js.map
  86277. /**
  86278. * Module Debug contains the (visual) components to debug a scene correctly
  86279. */
  86280. var BABYLON;
  86281. (function (BABYLON) {
  86282. var Debug;
  86283. (function (Debug) {
  86284. /**
  86285. * The Axes viewer will show 3 axes in a specific point in space
  86286. */
  86287. var AxesViewer = /** @class */ (function () {
  86288. /**
  86289. * Creates a new AxesViewer
  86290. * @param scene defines the hosting scene
  86291. * @param scaleLines defines a number used to scale line length (1 by default)
  86292. */
  86293. function AxesViewer(scene, scaleLines) {
  86294. if (scaleLines === void 0) { scaleLines = 1; }
  86295. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86296. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86297. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86298. /**
  86299. * Gets or sets a number used to scale line length
  86300. */
  86301. this.scaleLines = 1;
  86302. this.scaleLines = scaleLines;
  86303. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  86304. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  86305. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  86306. this._xmesh.renderingGroupId = 2;
  86307. this._ymesh.renderingGroupId = 2;
  86308. this._zmesh.renderingGroupId = 2;
  86309. this._xmesh.material.checkReadyOnlyOnce = true;
  86310. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  86311. this._ymesh.material.checkReadyOnlyOnce = true;
  86312. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  86313. this._zmesh.material.checkReadyOnlyOnce = true;
  86314. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  86315. this.scene = scene;
  86316. }
  86317. /**
  86318. * Force the viewer to update
  86319. * @param position defines the position of the viewer
  86320. * @param xaxis defines the x axis of the viewer
  86321. * @param yaxis defines the y axis of the viewer
  86322. * @param zaxis defines the z axis of the viewer
  86323. */
  86324. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  86325. var scaleLines = this.scaleLines;
  86326. if (this._xmesh) {
  86327. this._xmesh.position.copyFrom(position);
  86328. }
  86329. if (this._ymesh) {
  86330. this._ymesh.position.copyFrom(position);
  86331. }
  86332. if (this._zmesh) {
  86333. this._zmesh.position.copyFrom(position);
  86334. }
  86335. var point2 = this._xline[1];
  86336. point2.x = xaxis.x * scaleLines;
  86337. point2.y = xaxis.y * scaleLines;
  86338. point2.z = xaxis.z * scaleLines;
  86339. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  86340. point2 = this._yline[1];
  86341. point2.x = yaxis.x * scaleLines;
  86342. point2.y = yaxis.y * scaleLines;
  86343. point2.z = yaxis.z * scaleLines;
  86344. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  86345. point2 = this._zline[1];
  86346. point2.x = zaxis.x * scaleLines;
  86347. point2.y = zaxis.y * scaleLines;
  86348. point2.z = zaxis.z * scaleLines;
  86349. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  86350. };
  86351. /** Releases resources */
  86352. AxesViewer.prototype.dispose = function () {
  86353. if (this._xmesh) {
  86354. this._xmesh.dispose();
  86355. }
  86356. if (this._ymesh) {
  86357. this._ymesh.dispose();
  86358. }
  86359. if (this._zmesh) {
  86360. this._zmesh.dispose();
  86361. }
  86362. this._xmesh = null;
  86363. this._ymesh = null;
  86364. this._zmesh = null;
  86365. this.scene = null;
  86366. };
  86367. return AxesViewer;
  86368. }());
  86369. Debug.AxesViewer = AxesViewer;
  86370. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86371. })(BABYLON || (BABYLON = {}));
  86372. //# sourceMappingURL=babylon.axesViewer.js.map
  86373. var BABYLON;
  86374. (function (BABYLON) {
  86375. var Debug;
  86376. (function (Debug) {
  86377. /**
  86378. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  86379. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  86380. */
  86381. var BoneAxesViewer = /** @class */ (function (_super) {
  86382. __extends(BoneAxesViewer, _super);
  86383. /**
  86384. * Creates a new BoneAxesViewer
  86385. * @param scene defines the hosting scene
  86386. * @param bone defines the target bone
  86387. * @param mesh defines the target mesh
  86388. * @param scaleLines defines a scaling factor for line length (1 by default)
  86389. */
  86390. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  86391. if (scaleLines === void 0) { scaleLines = 1; }
  86392. var _this = _super.call(this, scene, scaleLines) || this;
  86393. /** Gets current position */
  86394. _this.pos = BABYLON.Vector3.Zero();
  86395. /** Gets direction of X axis */
  86396. _this.xaxis = BABYLON.Vector3.Zero();
  86397. /** Gets direction of Y axis */
  86398. _this.yaxis = BABYLON.Vector3.Zero();
  86399. /** Gets direction of Z axis */
  86400. _this.zaxis = BABYLON.Vector3.Zero();
  86401. _this.mesh = mesh;
  86402. _this.bone = bone;
  86403. return _this;
  86404. }
  86405. /**
  86406. * Force the viewer to update
  86407. */
  86408. BoneAxesViewer.prototype.update = function () {
  86409. if (!this.mesh || !this.bone) {
  86410. return;
  86411. }
  86412. var bone = this.bone;
  86413. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  86414. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  86415. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  86416. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  86417. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  86418. };
  86419. /** Releases resources */
  86420. BoneAxesViewer.prototype.dispose = function () {
  86421. if (this.mesh) {
  86422. this.mesh = null;
  86423. this.bone = null;
  86424. _super.prototype.dispose.call(this);
  86425. }
  86426. };
  86427. return BoneAxesViewer;
  86428. }(Debug.AxesViewer));
  86429. Debug.BoneAxesViewer = BoneAxesViewer;
  86430. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86431. })(BABYLON || (BABYLON = {}));
  86432. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  86433. var BABYLON;
  86434. (function (BABYLON) {
  86435. var RayHelper = /** @class */ (function () {
  86436. function RayHelper(ray) {
  86437. this.ray = ray;
  86438. }
  86439. RayHelper.CreateAndShow = function (ray, scene, color) {
  86440. var helper = new RayHelper(ray);
  86441. helper.show(scene, color);
  86442. return helper;
  86443. };
  86444. RayHelper.prototype.show = function (scene, color) {
  86445. if (!this._renderFunction && this.ray) {
  86446. var ray = this.ray;
  86447. this._renderFunction = this._render.bind(this);
  86448. this._scene = scene;
  86449. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  86450. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  86451. if (this._renderFunction) {
  86452. this._scene.registerBeforeRender(this._renderFunction);
  86453. }
  86454. }
  86455. if (color && this._renderLine) {
  86456. this._renderLine.color.copyFrom(color);
  86457. }
  86458. };
  86459. RayHelper.prototype.hide = function () {
  86460. if (this._renderFunction && this._scene) {
  86461. this._scene.unregisterBeforeRender(this._renderFunction);
  86462. this._scene = null;
  86463. this._renderFunction = null;
  86464. if (this._renderLine) {
  86465. this._renderLine.dispose();
  86466. this._renderLine = null;
  86467. }
  86468. this._renderPoints = [];
  86469. }
  86470. };
  86471. RayHelper.prototype._render = function () {
  86472. var ray = this.ray;
  86473. if (!ray) {
  86474. return;
  86475. }
  86476. var point = this._renderPoints[1];
  86477. var len = Math.min(ray.length, 1000000);
  86478. point.copyFrom(ray.direction);
  86479. point.scaleInPlace(len);
  86480. point.addInPlace(ray.origin);
  86481. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  86482. };
  86483. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  86484. this._attachedToMesh = mesh;
  86485. var ray = this.ray;
  86486. if (!ray) {
  86487. return;
  86488. }
  86489. if (!ray.direction) {
  86490. ray.direction = BABYLON.Vector3.Zero();
  86491. }
  86492. if (!ray.origin) {
  86493. ray.origin = BABYLON.Vector3.Zero();
  86494. }
  86495. if (length) {
  86496. ray.length = length;
  86497. }
  86498. if (!meshSpaceOrigin) {
  86499. meshSpaceOrigin = BABYLON.Vector3.Zero();
  86500. }
  86501. if (!meshSpaceDirection) {
  86502. // -1 so that this will work with Mesh.lookAt
  86503. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  86504. }
  86505. if (!this._meshSpaceDirection) {
  86506. this._meshSpaceDirection = meshSpaceDirection.clone();
  86507. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  86508. }
  86509. else {
  86510. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  86511. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  86512. }
  86513. if (!this._updateToMeshFunction) {
  86514. this._updateToMeshFunction = this._updateToMesh.bind(this);
  86515. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  86516. }
  86517. this._updateToMesh();
  86518. };
  86519. RayHelper.prototype.detachFromMesh = function () {
  86520. if (this._attachedToMesh) {
  86521. if (this._updateToMeshFunction) {
  86522. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  86523. }
  86524. this._attachedToMesh = null;
  86525. this._updateToMeshFunction = null;
  86526. }
  86527. };
  86528. RayHelper.prototype._updateToMesh = function () {
  86529. var ray = this.ray;
  86530. if (!this._attachedToMesh || !ray) {
  86531. return;
  86532. }
  86533. if (this._attachedToMesh._isDisposed) {
  86534. this.detachFromMesh();
  86535. return;
  86536. }
  86537. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  86538. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  86539. };
  86540. RayHelper.prototype.dispose = function () {
  86541. this.hide();
  86542. this.detachFromMesh();
  86543. this.ray = null;
  86544. };
  86545. return RayHelper;
  86546. }());
  86547. BABYLON.RayHelper = RayHelper;
  86548. })(BABYLON || (BABYLON = {}));
  86549. //# sourceMappingURL=babylon.rayHelper.js.map
  86550. var BABYLON;
  86551. (function (BABYLON) {
  86552. // load the inspector using require, if not present in the global namespace.
  86553. var DebugLayer = /** @class */ (function () {
  86554. function DebugLayer(scene) {
  86555. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86556. this._scene = scene;
  86557. // load inspector using require, if it doesn't exist on the global namespace.
  86558. }
  86559. /** Creates the inspector window. */
  86560. DebugLayer.prototype._createInspector = function (config) {
  86561. if (config === void 0) { config = {}; }
  86562. var popup = config.popup || false;
  86563. var initialTab = config.initialTab || 0;
  86564. var parentElement = config.parentElement || null;
  86565. if (!this._inspector) {
  86566. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  86567. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  86568. } // else nothing to do,; instance is already existing
  86569. };
  86570. DebugLayer.prototype.isVisible = function () {
  86571. if (!this._inspector) {
  86572. return false;
  86573. }
  86574. return true;
  86575. };
  86576. DebugLayer.prototype.hide = function () {
  86577. if (this._inspector) {
  86578. try {
  86579. this._inspector.dispose();
  86580. }
  86581. catch (e) {
  86582. // If the inspector has been removed directly from the inspector tool
  86583. }
  86584. this._inspector = null;
  86585. }
  86586. };
  86587. /**
  86588. *
  86589. * Launch the debugLayer.
  86590. *
  86591. * initialTab:
  86592. * | Value | Tab Name |
  86593. * | --- | --- |
  86594. * | 0 | Scene |
  86595. * | 1 | Console |
  86596. * | 2 | Stats |
  86597. * | 3 | Textures |
  86598. * | 4 | Mesh |
  86599. * | 5 | Light |
  86600. * | 6 | Material |
  86601. * | 7 | GLTF |
  86602. * | 8 | GUI |
  86603. * | 9 | Physics |
  86604. * | 10 | Camera |
  86605. * | 11 | Audio |
  86606. *
  86607. */
  86608. DebugLayer.prototype.show = function (config) {
  86609. if (config === void 0) { config = {}; }
  86610. if (typeof this.BJSINSPECTOR == 'undefined') {
  86611. // Load inspector and add it to the DOM
  86612. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86613. }
  86614. else {
  86615. // Otherwise creates the inspector
  86616. this._createInspector(config);
  86617. }
  86618. };
  86619. /**
  86620. * Gets the active tab
  86621. * @return the index of the active tab or -1 if the inspector is hidden
  86622. */
  86623. DebugLayer.prototype.getActiveTab = function () {
  86624. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86625. };
  86626. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86627. return DebugLayer;
  86628. }());
  86629. BABYLON.DebugLayer = DebugLayer;
  86630. })(BABYLON || (BABYLON = {}));
  86631. //# sourceMappingURL=babylon.debugLayer.js.map
  86632. var BABYLON;
  86633. (function (BABYLON) {
  86634. var Debug;
  86635. (function (Debug) {
  86636. /**
  86637. * Used to show the physics impostor around the specific mesh
  86638. */
  86639. var PhysicsViewer = /** @class */ (function () {
  86640. /**
  86641. * Creates a new PhysicsViewer
  86642. * @param scene defines the hosting scene
  86643. */
  86644. function PhysicsViewer(scene) {
  86645. /** @hidden */
  86646. this._impostors = [];
  86647. /** @hidden */
  86648. this._meshes = [];
  86649. /** @hidden */
  86650. this._numMeshes = 0;
  86651. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86652. var physicEngine = this._scene.getPhysicsEngine();
  86653. if (physicEngine) {
  86654. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86655. }
  86656. }
  86657. /** @hidden */
  86658. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86659. var plugin = this._physicsEnginePlugin;
  86660. for (var i = 0; i < this._numMeshes; i++) {
  86661. var impostor = this._impostors[i];
  86662. if (!impostor) {
  86663. continue;
  86664. }
  86665. if (impostor.isDisposed) {
  86666. this.hideImpostor(this._impostors[i--]);
  86667. }
  86668. else {
  86669. var mesh = this._meshes[i];
  86670. if (mesh && plugin) {
  86671. plugin.syncMeshWithImpostor(mesh, impostor);
  86672. }
  86673. }
  86674. }
  86675. };
  86676. /**
  86677. * Renders a specified physic impostor
  86678. * @param impostor defines the impostor to render
  86679. */
  86680. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86681. if (!this._scene) {
  86682. return;
  86683. }
  86684. for (var i = 0; i < this._numMeshes; i++) {
  86685. if (this._impostors[i] == impostor) {
  86686. return;
  86687. }
  86688. }
  86689. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86690. if (debugMesh) {
  86691. this._impostors[this._numMeshes] = impostor;
  86692. this._meshes[this._numMeshes] = debugMesh;
  86693. if (this._numMeshes === 0) {
  86694. this._renderFunction = this._updateDebugMeshes.bind(this);
  86695. this._scene.registerBeforeRender(this._renderFunction);
  86696. }
  86697. this._numMeshes++;
  86698. }
  86699. };
  86700. /**
  86701. * Hides a specified physic impostor
  86702. * @param impostor defines the impostor to hide
  86703. */
  86704. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86705. if (!impostor || !this._scene) {
  86706. return;
  86707. }
  86708. var removed = false;
  86709. for (var i = 0; i < this._numMeshes; i++) {
  86710. if (this._impostors[i] == impostor) {
  86711. var mesh = this._meshes[i];
  86712. if (!mesh) {
  86713. continue;
  86714. }
  86715. this._scene.removeMesh(mesh);
  86716. mesh.dispose();
  86717. this._numMeshes--;
  86718. if (this._numMeshes > 0) {
  86719. this._meshes[i] = this._meshes[this._numMeshes];
  86720. this._impostors[i] = this._impostors[this._numMeshes];
  86721. this._meshes[this._numMeshes] = null;
  86722. this._impostors[this._numMeshes] = null;
  86723. }
  86724. else {
  86725. this._meshes[0] = null;
  86726. this._impostors[0] = null;
  86727. }
  86728. removed = true;
  86729. break;
  86730. }
  86731. }
  86732. if (removed && this._numMeshes === 0) {
  86733. this._scene.unregisterBeforeRender(this._renderFunction);
  86734. }
  86735. };
  86736. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86737. if (!this._debugMaterial) {
  86738. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86739. this._debugMaterial.wireframe = true;
  86740. }
  86741. return this._debugMaterial;
  86742. };
  86743. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86744. if (!this._debugBoxMesh) {
  86745. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86746. this._debugBoxMesh.renderingGroupId = 1;
  86747. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86748. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86749. scene.removeMesh(this._debugBoxMesh);
  86750. }
  86751. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86752. };
  86753. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86754. if (!this._debugSphereMesh) {
  86755. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86756. this._debugSphereMesh.renderingGroupId = 1;
  86757. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86758. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86759. scene.removeMesh(this._debugSphereMesh);
  86760. }
  86761. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86762. };
  86763. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86764. var mesh = null;
  86765. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86766. mesh = this._getDebugBoxMesh(scene);
  86767. impostor.getBoxSizeToRef(mesh.scaling);
  86768. }
  86769. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86770. mesh = this._getDebugSphereMesh(scene);
  86771. var radius = impostor.getRadius();
  86772. mesh.scaling.x = radius * 2;
  86773. mesh.scaling.y = radius * 2;
  86774. mesh.scaling.z = radius * 2;
  86775. }
  86776. return mesh;
  86777. };
  86778. /** Releases all resources */
  86779. PhysicsViewer.prototype.dispose = function () {
  86780. for (var i = 0; i < this._numMeshes; i++) {
  86781. this.hideImpostor(this._impostors[i]);
  86782. }
  86783. if (this._debugBoxMesh) {
  86784. this._debugBoxMesh.dispose();
  86785. }
  86786. if (this._debugSphereMesh) {
  86787. this._debugSphereMesh.dispose();
  86788. }
  86789. if (this._debugMaterial) {
  86790. this._debugMaterial.dispose();
  86791. }
  86792. this._impostors.length = 0;
  86793. this._scene = null;
  86794. this._physicsEnginePlugin = null;
  86795. };
  86796. return PhysicsViewer;
  86797. }());
  86798. Debug.PhysicsViewer = PhysicsViewer;
  86799. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86800. })(BABYLON || (BABYLON = {}));
  86801. //# sourceMappingURL=babylon.physicsViewer.js.map
  86802. var BABYLON;
  86803. (function (BABYLON) {
  86804. var BoundingBoxRenderer = /** @class */ (function () {
  86805. function BoundingBoxRenderer(scene) {
  86806. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86807. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86808. this.showBackLines = true;
  86809. this.renderList = new BABYLON.SmartArray(32);
  86810. this._vertexBuffers = {};
  86811. this._scene = scene;
  86812. }
  86813. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86814. if (this._colorShader) {
  86815. return;
  86816. }
  86817. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86818. attributes: [BABYLON.VertexBuffer.PositionKind],
  86819. uniforms: ["world", "viewProjection", "color"]
  86820. });
  86821. var engine = this._scene.getEngine();
  86822. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86823. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86824. this._createIndexBuffer();
  86825. };
  86826. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86827. var engine = this._scene.getEngine();
  86828. 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]);
  86829. };
  86830. BoundingBoxRenderer.prototype._rebuild = function () {
  86831. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86832. if (vb) {
  86833. vb._rebuild();
  86834. }
  86835. this._createIndexBuffer();
  86836. };
  86837. BoundingBoxRenderer.prototype.reset = function () {
  86838. this.renderList.reset();
  86839. };
  86840. BoundingBoxRenderer.prototype.render = function () {
  86841. if (this.renderList.length === 0) {
  86842. return;
  86843. }
  86844. this._prepareRessources();
  86845. if (!this._colorShader.isReady()) {
  86846. return;
  86847. }
  86848. var engine = this._scene.getEngine();
  86849. engine.setDepthWrite(false);
  86850. this._colorShader._preBind();
  86851. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86852. var boundingBox = this.renderList.data[boundingBoxIndex];
  86853. var min = boundingBox.minimum;
  86854. var max = boundingBox.maximum;
  86855. var diff = max.subtract(min);
  86856. var median = min.add(diff.scale(0.5));
  86857. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86858. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86859. .multiply(boundingBox.getWorldMatrix());
  86860. // VBOs
  86861. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86862. if (this.showBackLines) {
  86863. // Back
  86864. engine.setDepthFunctionToGreaterOrEqual();
  86865. this._scene.resetCachedMaterial();
  86866. this._colorShader.setColor4("color", this.backColor.toColor4());
  86867. this._colorShader.bind(worldMatrix);
  86868. // Draw order
  86869. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86870. }
  86871. // Front
  86872. engine.setDepthFunctionToLess();
  86873. this._scene.resetCachedMaterial();
  86874. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86875. this._colorShader.bind(worldMatrix);
  86876. // Draw order
  86877. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86878. }
  86879. this._colorShader.unbind();
  86880. engine.setDepthFunctionToLessOrEqual();
  86881. engine.setDepthWrite(true);
  86882. };
  86883. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86884. this._prepareRessources();
  86885. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86886. return;
  86887. }
  86888. var engine = this._scene.getEngine();
  86889. engine.setDepthWrite(false);
  86890. engine.setColorWrite(false);
  86891. this._colorShader._preBind();
  86892. var boundingBox = mesh._boundingInfo.boundingBox;
  86893. var min = boundingBox.minimum;
  86894. var max = boundingBox.maximum;
  86895. var diff = max.subtract(min);
  86896. var median = min.add(diff.scale(0.5));
  86897. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86898. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86899. .multiply(boundingBox.getWorldMatrix());
  86900. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86901. engine.setDepthFunctionToLess();
  86902. this._scene.resetCachedMaterial();
  86903. this._colorShader.bind(worldMatrix);
  86904. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86905. this._colorShader.unbind();
  86906. engine.setDepthFunctionToLessOrEqual();
  86907. engine.setDepthWrite(true);
  86908. engine.setColorWrite(true);
  86909. };
  86910. BoundingBoxRenderer.prototype.dispose = function () {
  86911. if (!this._colorShader) {
  86912. return;
  86913. }
  86914. this.renderList.dispose();
  86915. this._colorShader.dispose();
  86916. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86917. if (buffer) {
  86918. buffer.dispose();
  86919. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86920. }
  86921. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86922. };
  86923. return BoundingBoxRenderer;
  86924. }());
  86925. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86926. })(BABYLON || (BABYLON = {}));
  86927. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86928. var BABYLON;
  86929. (function (BABYLON) {
  86930. /**
  86931. * Renders a layer on top of an existing scene
  86932. */
  86933. var UtilityLayerRenderer = /** @class */ (function () {
  86934. /**
  86935. * Instantiates a UtilityLayerRenderer
  86936. * @param originalScene the original scene that will be rendered on top of
  86937. */
  86938. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86939. var _this = this;
  86940. this.originalScene = originalScene;
  86941. this._pointerCaptures = {};
  86942. this._lastPointerEvents = {};
  86943. /**
  86944. * If the utility layer should automatically be rendered on top of existing scene
  86945. */
  86946. this.shouldRender = true;
  86947. /**
  86948. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  86949. */
  86950. this.onlyCheckPointerDownEvents = true;
  86951. /**
  86952. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  86953. */
  86954. this.processAllEvents = false;
  86955. /**
  86956. * Observable raised when the pointer move from the utility layer scene to the main scene
  86957. */
  86958. this.onPointerOutObservable = new BABYLON.Observable();
  86959. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86960. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86961. originalScene.getEngine().scenes.pop();
  86962. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  86963. this.utilityLayerScene.detachControl();
  86964. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  86965. if (!_this.processAllEvents) {
  86966. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  86967. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  86968. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  86969. return;
  86970. }
  86971. }
  86972. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  86973. if (!prePointerInfo.ray && utilityScenePick) {
  86974. prePointerInfo.ray = utilityScenePick.ray;
  86975. }
  86976. // always fire the prepointer oversvable
  86977. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  86978. // allow every non pointer down event to flow to the utility layer
  86979. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  86980. if (!prePointerInfo.skipOnPointerObservable) {
  86981. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  86982. }
  86983. return;
  86984. }
  86985. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  86986. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  86987. if (utilityScenePick && utilityScenePick.hit) {
  86988. if (!prePointerInfo.skipOnPointerObservable) {
  86989. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  86990. }
  86991. prePointerInfo.skipOnPointerObservable = true;
  86992. }
  86993. }
  86994. else {
  86995. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  86996. var pointerEvent = (prePointerInfo.event);
  86997. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  86998. if (originalScenePick && utilityScenePick) {
  86999. if (utilityScenePick.distance === 0) {
  87000. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87001. _this._pointerCaptures[pointerEvent.pointerId] = true;
  87002. }
  87003. }
  87004. if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87005. if (!prePointerInfo.skipOnPointerObservable) {
  87006. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87007. _this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87008. }
  87009. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87010. }
  87011. else if (!_this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87012. // We need to send a last pointup to the utilityLayerScene to make sure animations can complete
  87013. if (_this._lastPointerEvents[pointerEvent.pointerId]) {
  87014. _this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);
  87015. delete _this._lastPointerEvents[pointerEvent.pointerId];
  87016. }
  87017. }
  87018. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87019. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87020. }
  87021. }
  87022. }
  87023. });
  87024. // Render directly on top of existing scene without clearing
  87025. this.utilityLayerScene.autoClear = false;
  87026. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87027. if (_this.shouldRender) {
  87028. _this.render();
  87029. }
  87030. });
  87031. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87032. _this.dispose();
  87033. });
  87034. this._updateCamera();
  87035. }
  87036. /**
  87037. * Renders the utility layers scene on top of the original scene
  87038. */
  87039. UtilityLayerRenderer.prototype.render = function () {
  87040. this._updateCamera();
  87041. this.utilityLayerScene.render(false);
  87042. };
  87043. /**
  87044. * Disposes of the renderer
  87045. */
  87046. UtilityLayerRenderer.prototype.dispose = function () {
  87047. this.onPointerOutObservable.clear();
  87048. if (this._afterRenderObserver) {
  87049. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87050. }
  87051. if (this._sceneDisposeObserver) {
  87052. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87053. }
  87054. if (this._originalPointerObserver) {
  87055. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87056. }
  87057. this.utilityLayerScene.dispose();
  87058. };
  87059. UtilityLayerRenderer.prototype._updateCamera = function () {
  87060. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87061. };
  87062. return UtilityLayerRenderer;
  87063. }());
  87064. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87065. })(BABYLON || (BABYLON = {}));
  87066. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87067. var BABYLON;
  87068. (function (BABYLON) {
  87069. /**
  87070. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87071. */
  87072. var PointerDragBehavior = /** @class */ (function () {
  87073. /**
  87074. * Creates a pointer drag behavior that can be attached to a mesh
  87075. * @param options The drag axis or normal of the plane that will be dragged across.
  87076. */
  87077. function PointerDragBehavior(options) {
  87078. this.options = options;
  87079. this._draggingID = -1;
  87080. /**
  87081. * Fires each time the attached mesh is dragged with the pointer
  87082. */
  87083. this.onDragObservable = new BABYLON.Observable();
  87084. /**
  87085. * Fires each time a drag begins (eg. mouse down on mesh)
  87086. */
  87087. this.onDragStartObservable = new BABYLON.Observable();
  87088. /**
  87089. * Fires each time a drag ends (eg. mouse release after drag)
  87090. */
  87091. this.onDragEndObservable = new BABYLON.Observable();
  87092. /**
  87093. * If the attached mesh should be moved when dragged
  87094. */
  87095. this.moveAttached = true;
  87096. /**
  87097. * Mesh with the position where the drag plane should be placed
  87098. */
  87099. this._dragPlaneParent = null;
  87100. /**
  87101. * If the drag behavior will react to drag events
  87102. */
  87103. this.enabled = true;
  87104. var optionCount = 0;
  87105. if (options.dragAxis) {
  87106. optionCount++;
  87107. }
  87108. if (options.dragPlaneNormal) {
  87109. optionCount++;
  87110. }
  87111. if (optionCount > 1) {
  87112. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  87113. }
  87114. if (optionCount < 1) {
  87115. throw "At least one drag mode option must be specified";
  87116. }
  87117. }
  87118. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  87119. /**
  87120. * The name of the behavior
  87121. */
  87122. get: function () {
  87123. return "PointerDrag";
  87124. },
  87125. enumerable: true,
  87126. configurable: true
  87127. });
  87128. /**
  87129. * Initializes the behavior
  87130. */
  87131. PointerDragBehavior.prototype.init = function () { };
  87132. /**
  87133. * Attaches the drag behavior the passed in mesh
  87134. * @param ownerNode The mesh that will be dragged around once attached
  87135. */
  87136. PointerDragBehavior.prototype.attach = function (ownerNode) {
  87137. var _this = this;
  87138. this._scene = ownerNode.getScene();
  87139. this._attachedNode = ownerNode;
  87140. // Initialize drag plane to not interfere with existing scene
  87141. if (!PointerDragBehavior._planeScene) {
  87142. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  87143. this._scene.getEngine().scenes.pop();
  87144. }
  87145. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  87146. // State of the drag
  87147. var dragging = false;
  87148. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  87149. var delta = new BABYLON.Vector3(0, 0, 0);
  87150. var pickPredicate = function (m) {
  87151. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  87152. };
  87153. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  87154. if (!_this.enabled) {
  87155. return;
  87156. }
  87157. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87158. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  87159. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87160. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87161. if (pickedPoint) {
  87162. dragging = true;
  87163. _this._draggingID = pointerInfo.event.pointerId;
  87164. lastPosition.copyFrom(pickedPoint);
  87165. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  87166. }
  87167. }
  87168. }
  87169. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  87170. if (_this._draggingID == pointerInfo.event.pointerId) {
  87171. dragging = false;
  87172. _this._draggingID = -1;
  87173. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  87174. }
  87175. }
  87176. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  87177. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87178. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  87179. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  87180. if (pickedPoint) {
  87181. // depending on the drag mode option drag accordingly
  87182. if (_this.options.dragAxis) {
  87183. //get the closest point on the dragaxis from the selected mesh to the picked point location
  87184. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  87185. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  87186. }
  87187. else {
  87188. pickedPoint.subtractToRef(lastPosition, delta);
  87189. }
  87190. if (_this.moveAttached) {
  87191. _this._attachedNode.position.addInPlace(delta);
  87192. }
  87193. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  87194. lastPosition.copyFrom(pickedPoint);
  87195. }
  87196. }
  87197. }
  87198. });
  87199. };
  87200. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  87201. var _this = this;
  87202. if (!ray) {
  87203. return null;
  87204. }
  87205. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  87206. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  87207. return pickResult.pickedPoint;
  87208. }
  87209. else {
  87210. return null;
  87211. }
  87212. };
  87213. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  87214. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  87215. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  87216. if (this.options.dragAxis) {
  87217. var camPos = ray.origin;
  87218. // Calculate plane normal in direction of camera but perpendicular to drag axis
  87219. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  87220. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  87221. // Get perpendicular line from direction to camera and drag axis
  87222. var lineA = pointB.subtract(pointA);
  87223. var lineB = pointC.subtract(pointA);
  87224. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  87225. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  87226. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  87227. this._dragPlane.position.copyFrom(pointA);
  87228. this._dragPlane.lookAt(pointA.add(norm));
  87229. }
  87230. else if (this.options.dragPlaneNormal) {
  87231. this._dragPlane.position.copyFrom(pointA);
  87232. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  87233. }
  87234. this._dragPlane.computeWorldMatrix(true);
  87235. };
  87236. /**
  87237. * Detaches the behavior from the mesh
  87238. */
  87239. PointerDragBehavior.prototype.detach = function () {
  87240. if (this._pointerObserver) {
  87241. this._scene.onPointerObservable.remove(this._pointerObserver);
  87242. }
  87243. };
  87244. return PointerDragBehavior;
  87245. }());
  87246. BABYLON.PointerDragBehavior = PointerDragBehavior;
  87247. })(BABYLON || (BABYLON = {}));
  87248. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  87249. var BABYLON;
  87250. (function (BABYLON) {
  87251. /**
  87252. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  87253. */
  87254. var Gizmo = /** @class */ (function () {
  87255. /**
  87256. * Creates a gizmo
  87257. * @param gizmoLayer The utility layer the gizmo will be added to
  87258. */
  87259. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  87260. var _this = this;
  87261. this.gizmoLayer = gizmoLayer;
  87262. this._interactionsEnabled = true;
  87263. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  87264. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  87265. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  87266. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  87267. _this._rootMesh.scaling.set(dist, dist, dist);
  87268. }
  87269. if (_this.attachedMesh) {
  87270. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  87271. }
  87272. });
  87273. }
  87274. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87275. };
  87276. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  87277. get: function () {
  87278. return this._interactionsEnabled;
  87279. },
  87280. /**
  87281. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  87282. */
  87283. set: function (value) {
  87284. this._interactionsEnabled = value;
  87285. this._onInteractionsEnabledChanged(value);
  87286. },
  87287. enumerable: true,
  87288. configurable: true
  87289. });
  87290. /**
  87291. * Disposes of the gizmo
  87292. */
  87293. Gizmo.prototype.dispose = function () {
  87294. this._rootMesh.dispose();
  87295. if (this._beforeRenderObserver) {
  87296. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  87297. }
  87298. };
  87299. return Gizmo;
  87300. }());
  87301. BABYLON.Gizmo = Gizmo;
  87302. })(BABYLON || (BABYLON = {}));
  87303. //# sourceMappingURL=babylon.gizmo.js.map
  87304. var BABYLON;
  87305. (function (BABYLON) {
  87306. /**
  87307. * Single axis drag gizmo
  87308. */
  87309. var AxisDragGizmo = /** @class */ (function (_super) {
  87310. __extends(AxisDragGizmo, _super);
  87311. /**
  87312. * Creates an AxisDragGizmo
  87313. * @param gizmoLayer The utility layer the gizmo will be added to
  87314. * @param dragAxis The axis which the gizmo will be able to drag on
  87315. * @param color The color of the gizmo
  87316. */
  87317. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  87318. var _this = _super.call(this, gizmoLayer) || this;
  87319. // Create Material
  87320. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87321. coloredMaterial.disableLighting = true;
  87322. coloredMaterial.emissiveColor = color;
  87323. // Build mesh on root node
  87324. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87325. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87326. _this._rootMesh.addChild(arrowMesh);
  87327. _this._rootMesh.addChild(arrowTail);
  87328. // Position arrow pointing in its drag axis
  87329. arrowMesh.scaling.scaleInPlace(0.1);
  87330. arrowMesh.material = coloredMaterial;
  87331. arrowMesh.rotation.x = Math.PI / 2;
  87332. arrowMesh.position.z += 0.3;
  87333. arrowTail.rotation.x = Math.PI / 2;
  87334. arrowTail.material = coloredMaterial;
  87335. arrowTail.position.z += 0.2;
  87336. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87337. // Add drag behavior to handle events when the gizmo is dragged
  87338. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87339. _this._dragBehavior.moveAttached = false;
  87340. _this._rootMesh.addBehavior(_this._dragBehavior);
  87341. _this._dragBehavior.onDragObservable.add(function (event) {
  87342. if (!_this.interactionsEnabled) {
  87343. return;
  87344. }
  87345. if (_this.attachedMesh) {
  87346. _this.attachedMesh.position.addInPlace(event.delta);
  87347. }
  87348. });
  87349. return _this;
  87350. }
  87351. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87352. this._dragBehavior.enabled = value;
  87353. };
  87354. /**
  87355. * Disposes of the gizmo
  87356. */
  87357. AxisDragGizmo.prototype.dispose = function () {
  87358. this._dragBehavior.detach();
  87359. _super.prototype.dispose.call(this);
  87360. };
  87361. return AxisDragGizmo;
  87362. }(BABYLON.Gizmo));
  87363. BABYLON.AxisDragGizmo = AxisDragGizmo;
  87364. })(BABYLON || (BABYLON = {}));
  87365. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  87366. var BABYLON;
  87367. (function (BABYLON) {
  87368. /**
  87369. * Single axis scale gizmo
  87370. */
  87371. var AxisScaleGizmo = /** @class */ (function (_super) {
  87372. __extends(AxisScaleGizmo, _super);
  87373. /**
  87374. * Creates an AxisScaleGizmo
  87375. * @param gizmoLayer The utility layer the gizmo will be added to
  87376. * @param dragAxis The axis which the gizmo will be able to scale on
  87377. * @param color The color of the gizmo
  87378. */
  87379. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  87380. var _this = _super.call(this, gizmoLayer) || this;
  87381. // Create Material
  87382. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87383. coloredMaterial.disableLighting = true;
  87384. coloredMaterial.emissiveColor = color;
  87385. // Build mesh on root node
  87386. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  87387. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  87388. _this._rootMesh.addChild(arrowMesh);
  87389. _this._rootMesh.addChild(arrowTail);
  87390. // Position arrow pointing in its drag axis
  87391. arrowMesh.scaling.scaleInPlace(0.1);
  87392. arrowMesh.material = coloredMaterial;
  87393. arrowMesh.rotation.x = Math.PI / 2;
  87394. arrowMesh.position.z += 0.3;
  87395. arrowTail.rotation.x = Math.PI / 2;
  87396. arrowTail.material = coloredMaterial;
  87397. arrowTail.position.z += 0.2;
  87398. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  87399. // Add drag behavior to handle events when the gizmo is dragged
  87400. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  87401. _this._dragBehavior.moveAttached = false;
  87402. _this._rootMesh.addBehavior(_this._dragBehavior);
  87403. _this._dragBehavior.onDragObservable.add(function (event) {
  87404. if (!_this.interactionsEnabled) {
  87405. return;
  87406. }
  87407. if (_this.attachedMesh) {
  87408. _this.attachedMesh.scaling.addInPlace(event.delta);
  87409. }
  87410. });
  87411. return _this;
  87412. }
  87413. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87414. this._dragBehavior.enabled = value;
  87415. };
  87416. /**
  87417. * Disposes of the gizmo
  87418. */
  87419. AxisScaleGizmo.prototype.dispose = function () {
  87420. this._dragBehavior.detach();
  87421. _super.prototype.dispose.call(this);
  87422. };
  87423. return AxisScaleGizmo;
  87424. }(BABYLON.Gizmo));
  87425. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  87426. })(BABYLON || (BABYLON = {}));
  87427. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  87428. var BABYLON;
  87429. (function (BABYLON) {
  87430. /**
  87431. * Single plane rotation gizmo
  87432. */
  87433. var PlaneRotationGizmo = /** @class */ (function (_super) {
  87434. __extends(PlaneRotationGizmo, _super);
  87435. /**
  87436. * Creates a PlaneRotationGizmo
  87437. * @param gizmoLayer The utility layer the gizmo will be added to
  87438. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  87439. * @param color The color of the gizmo
  87440. */
  87441. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  87442. var _this = _super.call(this, gizmoLayer) || this;
  87443. // Create Material
  87444. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  87445. coloredMaterial.disableLighting = true;
  87446. coloredMaterial.emissiveColor = color;
  87447. // Build mesh on root node
  87448. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  87449. _this._rootMesh.addChild(rotationMesh);
  87450. // Position arrow pointing in its drag axis
  87451. rotationMesh.scaling.scaleInPlace(0.1);
  87452. rotationMesh.material = coloredMaterial;
  87453. rotationMesh.rotation.x = Math.PI / 2;
  87454. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  87455. // Add drag behavior to handle events when the gizmo is dragged
  87456. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  87457. _this._dragBehavior.moveAttached = false;
  87458. _this._rootMesh.addBehavior(_this._dragBehavior);
  87459. var lastDragPosition = null;
  87460. _this._dragBehavior.onDragStartObservable.add(function (e) {
  87461. if (!_this.interactionsEnabled) {
  87462. return;
  87463. }
  87464. lastDragPosition = e.dragPlanePoint;
  87465. });
  87466. _this._dragBehavior.onDragObservable.add(function (event) {
  87467. if (!_this.interactionsEnabled) {
  87468. return;
  87469. }
  87470. if (_this.attachedMesh && lastDragPosition) {
  87471. if (!_this.attachedMesh.rotationQuaternion) {
  87472. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  87473. }
  87474. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  87475. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  87476. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  87477. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  87478. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  87479. var angle = Math.atan2(cross.length(), dot);
  87480. var up = planeNormal.clone();
  87481. // Flip up vector depending on which side the camera is on
  87482. if (gizmoLayer.utilityLayerScene.activeCamera) {
  87483. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  87484. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  87485. up.scaleInPlace(-1);
  87486. }
  87487. }
  87488. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  87489. if (halfCircleSide)
  87490. angle = -angle;
  87491. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  87492. var quaternionCoefficient = Math.sin(angle / 2);
  87493. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  87494. // Rotate selected mesh quaternion over fixed axis
  87495. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  87496. lastDragPosition = event.dragPlanePoint;
  87497. }
  87498. });
  87499. return _this;
  87500. }
  87501. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87502. this._dragBehavior.enabled = value;
  87503. };
  87504. /**
  87505. * Disposes of the gizmo
  87506. */
  87507. PlaneRotationGizmo.prototype.dispose = function () {
  87508. this._dragBehavior.detach();
  87509. _super.prototype.dispose.call(this);
  87510. };
  87511. return PlaneRotationGizmo;
  87512. }(BABYLON.Gizmo));
  87513. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  87514. })(BABYLON || (BABYLON = {}));
  87515. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  87516. var BABYLON;
  87517. (function (BABYLON) {
  87518. /**
  87519. * Gizmo that enables dragging a mesh along 3 axis
  87520. */
  87521. var PositionGizmo = /** @class */ (function (_super) {
  87522. __extends(PositionGizmo, _super);
  87523. /**
  87524. * Creates a PositionGizmo
  87525. * @param gizmoLayer The utility layer the gizmo will be added to
  87526. */
  87527. function PositionGizmo(gizmoLayer) {
  87528. var _this = _super.call(this, gizmoLayer) || this;
  87529. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87530. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87531. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87532. return _this;
  87533. }
  87534. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  87535. set: function (mesh) {
  87536. this._xDrag.attachedMesh = mesh;
  87537. this._yDrag.attachedMesh = mesh;
  87538. this._zDrag.attachedMesh = mesh;
  87539. },
  87540. enumerable: true,
  87541. configurable: true
  87542. });
  87543. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87544. this._xDrag.interactionsEnabled = value;
  87545. this._yDrag.interactionsEnabled = value;
  87546. this._zDrag.interactionsEnabled = value;
  87547. };
  87548. /**
  87549. * Disposes of the gizmo
  87550. */
  87551. PositionGizmo.prototype.dispose = function () {
  87552. this._xDrag.dispose();
  87553. this._yDrag.dispose();
  87554. this._zDrag.dispose();
  87555. };
  87556. return PositionGizmo;
  87557. }(BABYLON.Gizmo));
  87558. BABYLON.PositionGizmo = PositionGizmo;
  87559. })(BABYLON || (BABYLON = {}));
  87560. //# sourceMappingURL=babylon.positionGizmo.js.map
  87561. var BABYLON;
  87562. (function (BABYLON) {
  87563. /**
  87564. * Gizmo that enables rotating a mesh along 3 axis
  87565. */
  87566. var RotationGizmo = /** @class */ (function (_super) {
  87567. __extends(RotationGizmo, _super);
  87568. /**
  87569. * Creates a RotationGizmo
  87570. * @param gizmoLayer The utility layer the gizmo will be added to
  87571. */
  87572. function RotationGizmo(gizmoLayer) {
  87573. var _this = _super.call(this, gizmoLayer) || this;
  87574. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87575. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87576. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87577. return _this;
  87578. }
  87579. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  87580. set: function (mesh) {
  87581. this._xDrag.attachedMesh = mesh;
  87582. this._yDrag.attachedMesh = mesh;
  87583. this._zDrag.attachedMesh = mesh;
  87584. },
  87585. enumerable: true,
  87586. configurable: true
  87587. });
  87588. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87589. this._xDrag.interactionsEnabled = value;
  87590. this._yDrag.interactionsEnabled = value;
  87591. this._zDrag.interactionsEnabled = value;
  87592. };
  87593. /**
  87594. * Disposes of the gizmo
  87595. */
  87596. RotationGizmo.prototype.dispose = function () {
  87597. this._xDrag.dispose();
  87598. this._yDrag.dispose();
  87599. this._zDrag.dispose();
  87600. };
  87601. return RotationGizmo;
  87602. }(BABYLON.Gizmo));
  87603. BABYLON.RotationGizmo = RotationGizmo;
  87604. })(BABYLON || (BABYLON = {}));
  87605. //# sourceMappingURL=babylon.rotationGizmo.js.map
  87606. var BABYLON;
  87607. (function (BABYLON) {
  87608. /**
  87609. * Gizmo that enables scaling a mesh along 3 axis
  87610. */
  87611. var ScaleGizmo = /** @class */ (function (_super) {
  87612. __extends(ScaleGizmo, _super);
  87613. /**
  87614. * Creates a ScaleGizmo
  87615. * @param gizmoLayer The utility layer the gizmo will be added to
  87616. */
  87617. function ScaleGizmo(gizmoLayer) {
  87618. var _this = _super.call(this, gizmoLayer) || this;
  87619. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  87620. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  87621. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  87622. return _this;
  87623. }
  87624. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  87625. set: function (mesh) {
  87626. this._xDrag.attachedMesh = mesh;
  87627. this._yDrag.attachedMesh = mesh;
  87628. this._zDrag.attachedMesh = mesh;
  87629. },
  87630. enumerable: true,
  87631. configurable: true
  87632. });
  87633. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  87634. this._xDrag.interactionsEnabled = value;
  87635. this._yDrag.interactionsEnabled = value;
  87636. this._zDrag.interactionsEnabled = value;
  87637. };
  87638. /**
  87639. * Disposes of the gizmo
  87640. */
  87641. ScaleGizmo.prototype.dispose = function () {
  87642. this._xDrag.dispose();
  87643. this._yDrag.dispose();
  87644. this._zDrag.dispose();
  87645. };
  87646. return ScaleGizmo;
  87647. }(BABYLON.Gizmo));
  87648. BABYLON.ScaleGizmo = ScaleGizmo;
  87649. })(BABYLON || (BABYLON = {}));
  87650. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87651. var BABYLON;
  87652. (function (BABYLON) {
  87653. /**
  87654. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  87655. */
  87656. var GizmoManager = /** @class */ (function () {
  87657. /**
  87658. * Instatiates a gizmo manager
  87659. * @param scene the scene to overlay the gizmos on top of
  87660. * @param options If only a single gizmo should exist at one time
  87661. */
  87662. function GizmoManager(scene, options) {
  87663. var _this = this;
  87664. this.scene = scene;
  87665. // Set of gizmos that are currently in the scene for each mesh
  87666. this._gizmoSet = {};
  87667. this._pointerObserver = null;
  87668. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  87669. // Options parsing
  87670. if (!options) {
  87671. options = {};
  87672. }
  87673. if (options.singleGizmo === undefined) {
  87674. options.singleGizmo = true;
  87675. }
  87676. // Instatiate/dispose gizmos based on pointer actions
  87677. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  87678. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87679. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  87680. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  87681. if (options.singleGizmo) {
  87682. _this._clearGizmos();
  87683. }
  87684. // Enable gizmo when mesh is selected
  87685. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  87686. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87687. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87688. }
  87689. else {
  87690. if (!options.singleGizmo) {
  87691. // Disable gizmo when clicked again
  87692. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  87693. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  87694. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  87695. }
  87696. }
  87697. }
  87698. else {
  87699. if (options.singleGizmo) {
  87700. // Disable gizmo when clicked away
  87701. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87702. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  87703. if (gizmoPick && !gizmoPick.hit) {
  87704. _this._clearGizmos();
  87705. }
  87706. }
  87707. }
  87708. }
  87709. }
  87710. });
  87711. }
  87712. /**
  87713. * Disposes of the gizmo manager
  87714. */
  87715. GizmoManager.prototype.dispose = function () {
  87716. this.scene.onPointerObservable.remove(this._pointerObserver);
  87717. this._clearGizmos();
  87718. this._gizmoLayer.dispose();
  87719. };
  87720. GizmoManager.prototype._clearGizmos = function () {
  87721. for (var key in this._gizmoSet) {
  87722. if (this._gizmoSet.hasOwnProperty(key)) {
  87723. this._gizmoSet[key].positionGizmo.dispose();
  87724. this._gizmoSet[key].rotationGizmo.dispose();
  87725. delete this._gizmoSet[key];
  87726. }
  87727. }
  87728. };
  87729. return GizmoManager;
  87730. }());
  87731. BABYLON.GizmoManager = GizmoManager;
  87732. })(BABYLON || (BABYLON = {}));
  87733. //# sourceMappingURL=babylon.gizmoManager.js.map
  87734. var BABYLON;
  87735. (function (BABYLON) {
  87736. /**
  87737. * Defines a target to use with MorphTargetManager
  87738. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87739. */
  87740. var MorphTarget = /** @class */ (function () {
  87741. /**
  87742. * Creates a new MorphTarget
  87743. * @param name defines the name of the target
  87744. * @param influence defines the influence to use
  87745. */
  87746. function MorphTarget(
  87747. /** defines the name of the target */
  87748. name, influence, scene) {
  87749. if (influence === void 0) { influence = 0; }
  87750. if (scene === void 0) { scene = null; }
  87751. this.name = name;
  87752. /**
  87753. * Gets or sets the list of animations
  87754. */
  87755. this.animations = new Array();
  87756. this._positions = null;
  87757. this._normals = null;
  87758. this._tangents = null;
  87759. /**
  87760. * Observable raised when the influence changes
  87761. */
  87762. this.onInfluenceChanged = new BABYLON.Observable();
  87763. this._animationPropertiesOverride = null;
  87764. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87765. this.influence = influence;
  87766. }
  87767. Object.defineProperty(MorphTarget.prototype, "influence", {
  87768. /**
  87769. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  87770. */
  87771. get: function () {
  87772. return this._influence;
  87773. },
  87774. set: function (influence) {
  87775. if (this._influence === influence) {
  87776. return;
  87777. }
  87778. var previous = this._influence;
  87779. this._influence = influence;
  87780. if (this.onInfluenceChanged.hasObservers) {
  87781. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  87782. }
  87783. },
  87784. enumerable: true,
  87785. configurable: true
  87786. });
  87787. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  87788. /**
  87789. * Gets or sets the animation properties override
  87790. */
  87791. get: function () {
  87792. if (!this._animationPropertiesOverride && this._scene) {
  87793. return this._scene.animationPropertiesOverride;
  87794. }
  87795. return this._animationPropertiesOverride;
  87796. },
  87797. set: function (value) {
  87798. this._animationPropertiesOverride = value;
  87799. },
  87800. enumerable: true,
  87801. configurable: true
  87802. });
  87803. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  87804. /**
  87805. * Gets a boolean defining if the target contains position data
  87806. */
  87807. get: function () {
  87808. return !!this._positions;
  87809. },
  87810. enumerable: true,
  87811. configurable: true
  87812. });
  87813. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  87814. /**
  87815. * Gets a boolean defining if the target contains normal data
  87816. */
  87817. get: function () {
  87818. return !!this._normals;
  87819. },
  87820. enumerable: true,
  87821. configurable: true
  87822. });
  87823. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  87824. /**
  87825. * Gets a boolean defining if the target contains tangent data
  87826. */
  87827. get: function () {
  87828. return !!this._tangents;
  87829. },
  87830. enumerable: true,
  87831. configurable: true
  87832. });
  87833. /**
  87834. * Affects position data to this target
  87835. * @param data defines the position data to use
  87836. */
  87837. MorphTarget.prototype.setPositions = function (data) {
  87838. this._positions = data;
  87839. };
  87840. /**
  87841. * Gets the position data stored in this target
  87842. * @returns a FloatArray containing the position data (or null if not present)
  87843. */
  87844. MorphTarget.prototype.getPositions = function () {
  87845. return this._positions;
  87846. };
  87847. /**
  87848. * Affects normal data to this target
  87849. * @param data defines the normal data to use
  87850. */
  87851. MorphTarget.prototype.setNormals = function (data) {
  87852. this._normals = data;
  87853. };
  87854. /**
  87855. * Gets the normal data stored in this target
  87856. * @returns a FloatArray containing the normal data (or null if not present)
  87857. */
  87858. MorphTarget.prototype.getNormals = function () {
  87859. return this._normals;
  87860. };
  87861. /**
  87862. * Affects tangent data to this target
  87863. * @param data defines the tangent data to use
  87864. */
  87865. MorphTarget.prototype.setTangents = function (data) {
  87866. this._tangents = data;
  87867. };
  87868. /**
  87869. * Gets the tangent data stored in this target
  87870. * @returns a FloatArray containing the tangent data (or null if not present)
  87871. */
  87872. MorphTarget.prototype.getTangents = function () {
  87873. return this._tangents;
  87874. };
  87875. /**
  87876. * Serializes the current target into a Serialization object
  87877. * @returns the serialized object
  87878. */
  87879. MorphTarget.prototype.serialize = function () {
  87880. var serializationObject = {};
  87881. serializationObject.name = this.name;
  87882. serializationObject.influence = this.influence;
  87883. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  87884. if (this.hasNormals) {
  87885. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  87886. }
  87887. if (this.hasTangents) {
  87888. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  87889. }
  87890. // Animations
  87891. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  87892. return serializationObject;
  87893. };
  87894. // Statics
  87895. /**
  87896. * Creates a new target from serialized data
  87897. * @param serializationObject defines the serialized data to use
  87898. * @returns a new MorphTarget
  87899. */
  87900. MorphTarget.Parse = function (serializationObject) {
  87901. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  87902. result.setPositions(serializationObject.positions);
  87903. if (serializationObject.normals) {
  87904. result.setNormals(serializationObject.normals);
  87905. }
  87906. if (serializationObject.tangents) {
  87907. result.setTangents(serializationObject.tangents);
  87908. }
  87909. // Animations
  87910. if (serializationObject.animations) {
  87911. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  87912. var parsedAnimation = serializationObject.animations[animationIndex];
  87913. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  87914. }
  87915. }
  87916. return result;
  87917. };
  87918. /**
  87919. * Creates a MorphTarget from mesh data
  87920. * @param mesh defines the source mesh
  87921. * @param name defines the name to use for the new target
  87922. * @param influence defines the influence to attach to the target
  87923. * @returns a new MorphTarget
  87924. */
  87925. MorphTarget.FromMesh = function (mesh, name, influence) {
  87926. if (!name) {
  87927. name = mesh.name;
  87928. }
  87929. var result = new MorphTarget(name, influence, mesh.getScene());
  87930. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87931. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87932. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  87933. }
  87934. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  87935. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  87936. }
  87937. return result;
  87938. };
  87939. return MorphTarget;
  87940. }());
  87941. BABYLON.MorphTarget = MorphTarget;
  87942. })(BABYLON || (BABYLON = {}));
  87943. //# sourceMappingURL=babylon.morphTarget.js.map
  87944. var BABYLON;
  87945. (function (BABYLON) {
  87946. /**
  87947. * This class is used to deform meshes using morphing between different targets
  87948. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87949. */
  87950. var MorphTargetManager = /** @class */ (function () {
  87951. /**
  87952. * Creates a new MorphTargetManager
  87953. * @param scene defines the current scene
  87954. */
  87955. function MorphTargetManager(scene) {
  87956. if (scene === void 0) { scene = null; }
  87957. this._targets = new Array();
  87958. this._targetObservable = new Array();
  87959. this._activeTargets = new BABYLON.SmartArray(16);
  87960. this._supportsNormals = false;
  87961. this._supportsTangents = false;
  87962. this._vertexCount = 0;
  87963. this._uniqueId = 0;
  87964. this._tempInfluences = new Array();
  87965. if (!scene) {
  87966. scene = BABYLON.Engine.LastCreatedScene;
  87967. }
  87968. this._scene = scene;
  87969. if (this._scene) {
  87970. this._scene.morphTargetManagers.push(this);
  87971. this._uniqueId = this._scene.getUniqueId();
  87972. }
  87973. }
  87974. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  87975. /**
  87976. * Gets the unique ID of this manager
  87977. */
  87978. get: function () {
  87979. return this._uniqueId;
  87980. },
  87981. enumerable: true,
  87982. configurable: true
  87983. });
  87984. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  87985. /**
  87986. * Gets the number of vertices handled by this manager
  87987. */
  87988. get: function () {
  87989. return this._vertexCount;
  87990. },
  87991. enumerable: true,
  87992. configurable: true
  87993. });
  87994. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  87995. /**
  87996. * Gets a boolean indicating if this manager supports morphing of normals
  87997. */
  87998. get: function () {
  87999. return this._supportsNormals;
  88000. },
  88001. enumerable: true,
  88002. configurable: true
  88003. });
  88004. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  88005. /**
  88006. * Gets a boolean indicating if this manager supports morphing of tangents
  88007. */
  88008. get: function () {
  88009. return this._supportsTangents;
  88010. },
  88011. enumerable: true,
  88012. configurable: true
  88013. });
  88014. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  88015. /**
  88016. * Gets the number of targets stored in this manager
  88017. */
  88018. get: function () {
  88019. return this._targets.length;
  88020. },
  88021. enumerable: true,
  88022. configurable: true
  88023. });
  88024. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  88025. /**
  88026. * Gets the number of influencers (ie. the number of targets with influences > 0)
  88027. */
  88028. get: function () {
  88029. return this._activeTargets.length;
  88030. },
  88031. enumerable: true,
  88032. configurable: true
  88033. });
  88034. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  88035. /**
  88036. * Gets the list of influences (one per target)
  88037. */
  88038. get: function () {
  88039. return this._influences;
  88040. },
  88041. enumerable: true,
  88042. configurable: true
  88043. });
  88044. /**
  88045. * Gets the active target at specified index. An active target is a target with an influence > 0
  88046. * @param index defines the index to check
  88047. * @returns the requested target
  88048. */
  88049. MorphTargetManager.prototype.getActiveTarget = function (index) {
  88050. return this._activeTargets.data[index];
  88051. };
  88052. /**
  88053. * Gets the target at specified index
  88054. * @param index defines the index to check
  88055. * @returns the requested target
  88056. */
  88057. MorphTargetManager.prototype.getTarget = function (index) {
  88058. return this._targets[index];
  88059. };
  88060. /**
  88061. * Add a new target to this manager
  88062. * @param target defines the target to add
  88063. */
  88064. MorphTargetManager.prototype.addTarget = function (target) {
  88065. var _this = this;
  88066. this._targets.push(target);
  88067. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  88068. _this._syncActiveTargets(needUpdate);
  88069. }));
  88070. this._syncActiveTargets(true);
  88071. };
  88072. /**
  88073. * Removes a target from the manager
  88074. * @param target defines the target to remove
  88075. */
  88076. MorphTargetManager.prototype.removeTarget = function (target) {
  88077. var index = this._targets.indexOf(target);
  88078. if (index >= 0) {
  88079. this._targets.splice(index, 1);
  88080. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  88081. this._syncActiveTargets(true);
  88082. }
  88083. };
  88084. /**
  88085. * Serializes the current manager into a Serialization object
  88086. * @returns the serialized object
  88087. */
  88088. MorphTargetManager.prototype.serialize = function () {
  88089. var serializationObject = {};
  88090. serializationObject.id = this.uniqueId;
  88091. serializationObject.targets = [];
  88092. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88093. var target = _a[_i];
  88094. serializationObject.targets.push(target.serialize());
  88095. }
  88096. return serializationObject;
  88097. };
  88098. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  88099. var influenceCount = 0;
  88100. this._activeTargets.reset();
  88101. this._supportsNormals = true;
  88102. this._supportsTangents = true;
  88103. this._vertexCount = 0;
  88104. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  88105. var target = _a[_i];
  88106. this._activeTargets.push(target);
  88107. this._tempInfluences[influenceCount++] = target.influence;
  88108. var positions = target.getPositions();
  88109. if (positions) {
  88110. this._supportsNormals = this._supportsNormals && target.hasNormals;
  88111. this._supportsTangents = this._supportsTangents && target.hasTangents;
  88112. var vertexCount = positions.length / 3;
  88113. if (this._vertexCount === 0) {
  88114. this._vertexCount = vertexCount;
  88115. }
  88116. else if (this._vertexCount !== vertexCount) {
  88117. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  88118. return;
  88119. }
  88120. }
  88121. }
  88122. if (!this._influences || this._influences.length !== influenceCount) {
  88123. this._influences = new Float32Array(influenceCount);
  88124. }
  88125. for (var index = 0; index < influenceCount; index++) {
  88126. this._influences[index] = this._tempInfluences[index];
  88127. }
  88128. if (needUpdate) {
  88129. this.synchronize();
  88130. }
  88131. };
  88132. /**
  88133. * Syncrhonize the targets with all the meshes using this morph target manager
  88134. */
  88135. MorphTargetManager.prototype.synchronize = function () {
  88136. if (!this._scene) {
  88137. return;
  88138. }
  88139. // Flag meshes as dirty to resync with the active targets
  88140. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  88141. var mesh = _a[_i];
  88142. if (mesh.morphTargetManager === this) {
  88143. mesh._syncGeometryWithMorphTargetManager();
  88144. }
  88145. }
  88146. };
  88147. // Statics
  88148. /**
  88149. * Creates a new MorphTargetManager from serialized data
  88150. * @param serializationObject defines the serialized data
  88151. * @param scene defines the hosting scene
  88152. * @returns the new MorphTargetManager
  88153. */
  88154. MorphTargetManager.Parse = function (serializationObject, scene) {
  88155. var result = new MorphTargetManager(scene);
  88156. result._uniqueId = serializationObject.id;
  88157. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  88158. var targetData = _a[_i];
  88159. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  88160. }
  88161. return result;
  88162. };
  88163. return MorphTargetManager;
  88164. }());
  88165. BABYLON.MorphTargetManager = MorphTargetManager;
  88166. })(BABYLON || (BABYLON = {}));
  88167. //# sourceMappingURL=babylon.morphTargetManager.js.map
  88168. var BABYLON;
  88169. (function (BABYLON) {
  88170. var Octree = /** @class */ (function () {
  88171. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  88172. if (maxDepth === void 0) { maxDepth = 2; }
  88173. this.maxDepth = maxDepth;
  88174. this.dynamicContent = new Array();
  88175. this._maxBlockCapacity = maxBlockCapacity || 64;
  88176. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  88177. this._creationFunc = creationFunc;
  88178. }
  88179. // Methods
  88180. Octree.prototype.update = function (worldMin, worldMax, entries) {
  88181. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  88182. };
  88183. Octree.prototype.addMesh = function (entry) {
  88184. for (var index = 0; index < this.blocks.length; index++) {
  88185. var block = this.blocks[index];
  88186. block.addEntry(entry);
  88187. }
  88188. };
  88189. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  88190. this._selectionContent.reset();
  88191. for (var index = 0; index < this.blocks.length; index++) {
  88192. var block = this.blocks[index];
  88193. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  88194. }
  88195. if (allowDuplicate) {
  88196. this._selectionContent.concat(this.dynamicContent);
  88197. }
  88198. else {
  88199. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88200. }
  88201. return this._selectionContent;
  88202. };
  88203. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  88204. this._selectionContent.reset();
  88205. for (var index = 0; index < this.blocks.length; index++) {
  88206. var block = this.blocks[index];
  88207. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  88208. }
  88209. if (allowDuplicate) {
  88210. this._selectionContent.concat(this.dynamicContent);
  88211. }
  88212. else {
  88213. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88214. }
  88215. return this._selectionContent;
  88216. };
  88217. Octree.prototype.intersectsRay = function (ray) {
  88218. this._selectionContent.reset();
  88219. for (var index = 0; index < this.blocks.length; index++) {
  88220. var block = this.blocks[index];
  88221. block.intersectsRay(ray, this._selectionContent);
  88222. }
  88223. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  88224. return this._selectionContent;
  88225. };
  88226. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  88227. target.blocks = new Array();
  88228. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  88229. // Segmenting space
  88230. for (var x = 0; x < 2; x++) {
  88231. for (var y = 0; y < 2; y++) {
  88232. for (var z = 0; z < 2; z++) {
  88233. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  88234. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  88235. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  88236. block.addEntries(entries);
  88237. target.blocks.push(block);
  88238. }
  88239. }
  88240. }
  88241. };
  88242. Octree.CreationFuncForMeshes = function (entry, block) {
  88243. var boundingInfo = entry.getBoundingInfo();
  88244. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88245. block.entries.push(entry);
  88246. }
  88247. };
  88248. Octree.CreationFuncForSubMeshes = function (entry, block) {
  88249. var boundingInfo = entry.getBoundingInfo();
  88250. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  88251. block.entries.push(entry);
  88252. }
  88253. };
  88254. return Octree;
  88255. }());
  88256. BABYLON.Octree = Octree;
  88257. })(BABYLON || (BABYLON = {}));
  88258. //# sourceMappingURL=babylon.octree.js.map
  88259. var BABYLON;
  88260. (function (BABYLON) {
  88261. var OctreeBlock = /** @class */ (function () {
  88262. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  88263. this.entries = new Array();
  88264. this._boundingVectors = new Array();
  88265. this._capacity = capacity;
  88266. this._depth = depth;
  88267. this._maxDepth = maxDepth;
  88268. this._creationFunc = creationFunc;
  88269. this._minPoint = minPoint;
  88270. this._maxPoint = maxPoint;
  88271. this._boundingVectors.push(minPoint.clone());
  88272. this._boundingVectors.push(maxPoint.clone());
  88273. this._boundingVectors.push(minPoint.clone());
  88274. this._boundingVectors[2].x = maxPoint.x;
  88275. this._boundingVectors.push(minPoint.clone());
  88276. this._boundingVectors[3].y = maxPoint.y;
  88277. this._boundingVectors.push(minPoint.clone());
  88278. this._boundingVectors[4].z = maxPoint.z;
  88279. this._boundingVectors.push(maxPoint.clone());
  88280. this._boundingVectors[5].z = minPoint.z;
  88281. this._boundingVectors.push(maxPoint.clone());
  88282. this._boundingVectors[6].x = minPoint.x;
  88283. this._boundingVectors.push(maxPoint.clone());
  88284. this._boundingVectors[7].y = minPoint.y;
  88285. }
  88286. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  88287. // Property
  88288. get: function () {
  88289. return this._capacity;
  88290. },
  88291. enumerable: true,
  88292. configurable: true
  88293. });
  88294. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  88295. get: function () {
  88296. return this._minPoint;
  88297. },
  88298. enumerable: true,
  88299. configurable: true
  88300. });
  88301. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  88302. get: function () {
  88303. return this._maxPoint;
  88304. },
  88305. enumerable: true,
  88306. configurable: true
  88307. });
  88308. // Methods
  88309. OctreeBlock.prototype.addEntry = function (entry) {
  88310. if (this.blocks) {
  88311. for (var index = 0; index < this.blocks.length; index++) {
  88312. var block = this.blocks[index];
  88313. block.addEntry(entry);
  88314. }
  88315. return;
  88316. }
  88317. this._creationFunc(entry, this);
  88318. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  88319. this.createInnerBlocks();
  88320. }
  88321. };
  88322. OctreeBlock.prototype.addEntries = function (entries) {
  88323. for (var index = 0; index < entries.length; index++) {
  88324. var mesh = entries[index];
  88325. this.addEntry(mesh);
  88326. }
  88327. };
  88328. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  88329. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  88330. if (this.blocks) {
  88331. for (var index = 0; index < this.blocks.length; index++) {
  88332. var block = this.blocks[index];
  88333. block.select(frustumPlanes, selection, allowDuplicate);
  88334. }
  88335. return;
  88336. }
  88337. if (allowDuplicate) {
  88338. selection.concat(this.entries);
  88339. }
  88340. else {
  88341. selection.concatWithNoDuplicate(this.entries);
  88342. }
  88343. }
  88344. };
  88345. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  88346. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  88347. if (this.blocks) {
  88348. for (var index = 0; index < this.blocks.length; index++) {
  88349. var block = this.blocks[index];
  88350. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  88351. }
  88352. return;
  88353. }
  88354. if (allowDuplicate) {
  88355. selection.concat(this.entries);
  88356. }
  88357. else {
  88358. selection.concatWithNoDuplicate(this.entries);
  88359. }
  88360. }
  88361. };
  88362. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  88363. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  88364. if (this.blocks) {
  88365. for (var index = 0; index < this.blocks.length; index++) {
  88366. var block = this.blocks[index];
  88367. block.intersectsRay(ray, selection);
  88368. }
  88369. return;
  88370. }
  88371. selection.concatWithNoDuplicate(this.entries);
  88372. }
  88373. };
  88374. OctreeBlock.prototype.createInnerBlocks = function () {
  88375. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  88376. };
  88377. return OctreeBlock;
  88378. }());
  88379. BABYLON.OctreeBlock = OctreeBlock;
  88380. })(BABYLON || (BABYLON = {}));
  88381. //# sourceMappingURL=babylon.octreeBlock.js.map
  88382. var BABYLON;
  88383. (function (BABYLON) {
  88384. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  88385. __extends(VRDistortionCorrectionPostProcess, _super);
  88386. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  88387. var _this = _super.call(this, name, "vrDistortionCorrection", [
  88388. 'LensCenter',
  88389. 'Scale',
  88390. 'ScaleIn',
  88391. 'HmdWarpParam'
  88392. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  88393. _this._isRightEye = isRightEye;
  88394. _this._distortionFactors = vrMetrics.distortionK;
  88395. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  88396. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  88397. _this.adaptScaleToCurrentViewport = true;
  88398. _this.onSizeChangedObservable.add(function () {
  88399. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  88400. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  88401. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  88402. });
  88403. _this.onApplyObservable.add(function (effect) {
  88404. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  88405. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  88406. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  88407. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  88408. });
  88409. return _this;
  88410. }
  88411. return VRDistortionCorrectionPostProcess;
  88412. }(BABYLON.PostProcess));
  88413. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  88414. })(BABYLON || (BABYLON = {}));
  88415. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  88416. var BABYLON;
  88417. (function (BABYLON) {
  88418. /**
  88419. * Postprocess used to generate anaglyphic rendering
  88420. */
  88421. var AnaglyphPostProcess = /** @class */ (function (_super) {
  88422. __extends(AnaglyphPostProcess, _super);
  88423. /**
  88424. * Creates a new AnaglyphPostProcess
  88425. * @param name defines postprocess name
  88426. * @param options defines creation options or target ratio scale
  88427. * @param rigCameras defines cameras using this postprocess
  88428. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  88429. * @param engine defines hosting engine
  88430. * @param reusable defines if the postprocess will be reused multiple times per frame
  88431. */
  88432. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  88433. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  88434. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88435. _this.onApplyObservable.add(function (effect) {
  88436. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  88437. });
  88438. return _this;
  88439. }
  88440. return AnaglyphPostProcess;
  88441. }(BABYLON.PostProcess));
  88442. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  88443. })(BABYLON || (BABYLON = {}));
  88444. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  88445. var BABYLON;
  88446. (function (BABYLON) {
  88447. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  88448. __extends(StereoscopicInterlacePostProcess, _super);
  88449. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  88450. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  88451. _this._passedProcess = rigCameras[0]._rigPostProcess;
  88452. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88453. _this.onSizeChangedObservable.add(function () {
  88454. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  88455. });
  88456. _this.onApplyObservable.add(function (effect) {
  88457. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  88458. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  88459. });
  88460. return _this;
  88461. }
  88462. return StereoscopicInterlacePostProcess;
  88463. }(BABYLON.PostProcess));
  88464. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  88465. })(BABYLON || (BABYLON = {}));
  88466. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  88467. var BABYLON;
  88468. (function (BABYLON) {
  88469. /**
  88470. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  88471. * Screen rotation is taken into account.
  88472. */
  88473. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  88474. function FreeCameraDeviceOrientationInput() {
  88475. var _this = this;
  88476. this._screenOrientationAngle = 0;
  88477. this._screenQuaternion = new BABYLON.Quaternion();
  88478. this._alpha = 0;
  88479. this._beta = 0;
  88480. this._gamma = 0;
  88481. this._orientationChanged = function () {
  88482. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  88483. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  88484. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  88485. };
  88486. this._deviceOrientation = function (evt) {
  88487. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  88488. _this._beta = evt.beta !== null ? evt.beta : 0;
  88489. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  88490. };
  88491. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  88492. this._orientationChanged();
  88493. }
  88494. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  88495. get: function () {
  88496. return this._camera;
  88497. },
  88498. set: function (camera) {
  88499. this._camera = camera;
  88500. if (this._camera != null && !this._camera.rotationQuaternion) {
  88501. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  88502. }
  88503. },
  88504. enumerable: true,
  88505. configurable: true
  88506. });
  88507. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88508. window.addEventListener("orientationchange", this._orientationChanged);
  88509. window.addEventListener("deviceorientation", this._deviceOrientation);
  88510. //In certain cases, the attach control is called AFTER orientation was changed,
  88511. //So this is needed.
  88512. this._orientationChanged();
  88513. };
  88514. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  88515. window.removeEventListener("orientationchange", this._orientationChanged);
  88516. window.removeEventListener("deviceorientation", this._deviceOrientation);
  88517. };
  88518. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  88519. //if no device orientation provided, don't update the rotation.
  88520. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  88521. if (!this._alpha)
  88522. return;
  88523. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  88524. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  88525. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  88526. //Mirror on XY Plane
  88527. this._camera.rotationQuaternion.z *= -1;
  88528. this._camera.rotationQuaternion.w *= -1;
  88529. };
  88530. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  88531. return "FreeCameraDeviceOrientationInput";
  88532. };
  88533. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  88534. return "deviceOrientation";
  88535. };
  88536. return FreeCameraDeviceOrientationInput;
  88537. }());
  88538. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  88539. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  88540. })(BABYLON || (BABYLON = {}));
  88541. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  88542. var BABYLON;
  88543. (function (BABYLON) {
  88544. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  88545. function ArcRotateCameraVRDeviceOrientationInput() {
  88546. this.alphaCorrection = 1;
  88547. this.betaCorrection = 1;
  88548. this.gammaCorrection = 1;
  88549. this._alpha = 0;
  88550. this._gamma = 0;
  88551. this._dirty = false;
  88552. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  88553. }
  88554. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  88555. this.camera.attachControl(element, noPreventDefault);
  88556. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  88557. };
  88558. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  88559. if (evt.alpha !== null) {
  88560. this._alpha = +evt.alpha | 0;
  88561. }
  88562. if (evt.gamma !== null) {
  88563. this._gamma = +evt.gamma | 0;
  88564. }
  88565. this._dirty = true;
  88566. };
  88567. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  88568. if (this._dirty) {
  88569. this._dirty = false;
  88570. if (this._gamma < 0) {
  88571. this._gamma = 180 + this._gamma;
  88572. }
  88573. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  88574. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  88575. }
  88576. };
  88577. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  88578. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  88579. };
  88580. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  88581. return "ArcRotateCameraVRDeviceOrientationInput";
  88582. };
  88583. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  88584. return "VRDeviceOrientation";
  88585. };
  88586. return ArcRotateCameraVRDeviceOrientationInput;
  88587. }());
  88588. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  88589. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  88590. })(BABYLON || (BABYLON = {}));
  88591. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  88592. var BABYLON;
  88593. (function (BABYLON) {
  88594. var VRCameraMetrics = /** @class */ (function () {
  88595. function VRCameraMetrics() {
  88596. this.compensateDistortion = true;
  88597. }
  88598. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  88599. get: function () {
  88600. return this.hResolution / (2 * this.vResolution);
  88601. },
  88602. enumerable: true,
  88603. configurable: true
  88604. });
  88605. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  88606. get: function () {
  88607. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  88608. },
  88609. enumerable: true,
  88610. configurable: true
  88611. });
  88612. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  88613. get: function () {
  88614. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88615. var h = (4 * meters) / this.hScreenSize;
  88616. return BABYLON.Matrix.Translation(h, 0, 0);
  88617. },
  88618. enumerable: true,
  88619. configurable: true
  88620. });
  88621. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  88622. get: function () {
  88623. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  88624. var h = (4 * meters) / this.hScreenSize;
  88625. return BABYLON.Matrix.Translation(-h, 0, 0);
  88626. },
  88627. enumerable: true,
  88628. configurable: true
  88629. });
  88630. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  88631. get: function () {
  88632. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  88633. },
  88634. enumerable: true,
  88635. configurable: true
  88636. });
  88637. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  88638. get: function () {
  88639. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  88640. },
  88641. enumerable: true,
  88642. configurable: true
  88643. });
  88644. VRCameraMetrics.GetDefault = function () {
  88645. var result = new VRCameraMetrics();
  88646. result.hResolution = 1280;
  88647. result.vResolution = 800;
  88648. result.hScreenSize = 0.149759993;
  88649. result.vScreenSize = 0.0935999975;
  88650. result.vScreenCenter = 0.0467999987;
  88651. result.eyeToScreenDistance = 0.0410000011;
  88652. result.lensSeparationDistance = 0.0635000020;
  88653. result.interpupillaryDistance = 0.0640000030;
  88654. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  88655. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  88656. result.postProcessScaleFactor = 1.714605507808412;
  88657. result.lensCenterOffset = 0.151976421;
  88658. return result;
  88659. };
  88660. return VRCameraMetrics;
  88661. }());
  88662. BABYLON.VRCameraMetrics = VRCameraMetrics;
  88663. })(BABYLON || (BABYLON = {}));
  88664. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  88665. var BABYLON;
  88666. (function (BABYLON) {
  88667. /**
  88668. * This represents a WebVR camera.
  88669. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  88670. * @example http://doc.babylonjs.com/how_to/webvr_camera
  88671. */
  88672. var WebVRFreeCamera = /** @class */ (function (_super) {
  88673. __extends(WebVRFreeCamera, _super);
  88674. /**
  88675. * Instantiates a WebVRFreeCamera.
  88676. * @param name The name of the WebVRFreeCamera
  88677. * @param position The starting anchor position for the camera
  88678. * @param scene The scene the camera belongs to
  88679. * @param webVROptions a set of customizable options for the webVRCamera
  88680. */
  88681. function WebVRFreeCamera(name, position, scene, webVROptions) {
  88682. if (webVROptions === void 0) { webVROptions = {}; }
  88683. var _this = _super.call(this, name, position, scene) || this;
  88684. _this.webVROptions = webVROptions;
  88685. /**
  88686. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  88687. */
  88688. _this._vrDevice = null;
  88689. /**
  88690. * The rawPose of the vrDevice.
  88691. */
  88692. _this.rawPose = null;
  88693. _this._specsVersion = "1.1";
  88694. _this._attached = false;
  88695. _this._descendants = [];
  88696. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  88697. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  88698. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  88699. _this._standingMatrix = null;
  88700. /**
  88701. * Represents device position in babylon space.
  88702. */
  88703. _this.devicePosition = BABYLON.Vector3.Zero();
  88704. /**
  88705. * Represents device rotation in babylon space.
  88706. */
  88707. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  88708. /**
  88709. * The scale of the device to be used when translating from device space to babylon space.
  88710. */
  88711. _this.deviceScaleFactor = 1;
  88712. _this._deviceToWorld = BABYLON.Matrix.Identity();
  88713. _this._worldToDevice = BABYLON.Matrix.Identity();
  88714. /**
  88715. * References to the webVR controllers for the vrDevice.
  88716. */
  88717. _this.controllers = [];
  88718. /**
  88719. * Emits an event when a controller is attached.
  88720. */
  88721. _this.onControllersAttachedObservable = new BABYLON.Observable();
  88722. /**
  88723. * Emits an event when a controller's mesh has been loaded;
  88724. */
  88725. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88726. /**
  88727. * If the rig cameras be used as parent instead of this camera.
  88728. */
  88729. _this.rigParenting = true;
  88730. _this._defaultHeight = undefined;
  88731. _this._workingVector = BABYLON.Vector3.Zero();
  88732. _this._oneVector = BABYLON.Vector3.One();
  88733. _this._workingMatrix = BABYLON.Matrix.Identity();
  88734. _this._cache.position = BABYLON.Vector3.Zero();
  88735. if (webVROptions.defaultHeight) {
  88736. _this._defaultHeight = webVROptions.defaultHeight;
  88737. _this.position.y = _this._defaultHeight;
  88738. }
  88739. _this.minZ = 0.1;
  88740. //legacy support - the compensation boolean was removed.
  88741. if (arguments.length === 5) {
  88742. _this.webVROptions = arguments[4];
  88743. }
  88744. // default webVR options
  88745. if (_this.webVROptions.trackPosition == undefined) {
  88746. _this.webVROptions.trackPosition = true;
  88747. }
  88748. if (_this.webVROptions.controllerMeshes == undefined) {
  88749. _this.webVROptions.controllerMeshes = true;
  88750. }
  88751. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  88752. _this.webVROptions.defaultLightingOnControllers = true;
  88753. }
  88754. _this.rotationQuaternion = new BABYLON.Quaternion();
  88755. if (_this.webVROptions && _this.webVROptions.positionScale) {
  88756. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  88757. }
  88758. //enable VR
  88759. var engine = _this.getEngine();
  88760. _this._onVREnabled = function (success) { if (success) {
  88761. _this.initControllers();
  88762. } };
  88763. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  88764. engine.initWebVR().add(function (event) {
  88765. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  88766. return;
  88767. }
  88768. _this._vrDevice = event.vrDisplay;
  88769. //reset the rig parameters.
  88770. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  88771. if (_this._attached) {
  88772. _this.getEngine().enableVR();
  88773. }
  88774. });
  88775. if (typeof (VRFrameData) !== "undefined")
  88776. _this._frameData = new VRFrameData();
  88777. /**
  88778. * The idea behind the following lines:
  88779. * objects that have the camera as parent should actually have the rig cameras as a parent.
  88780. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  88781. * the second will not show it correctly.
  88782. *
  88783. * To solve this - each object that has the camera as parent will be added to a protected array.
  88784. * When the rig camera renders, it will take this array and set all of those to be its children.
  88785. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  88786. * Amazing!
  88787. */
  88788. scene.onBeforeCameraRenderObservable.add(function (camera) {
  88789. if (camera.parent === _this && _this.rigParenting) {
  88790. _this._descendants = _this.getDescendants(true, function (n) {
  88791. // don't take the cameras or the controllers!
  88792. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  88793. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  88794. return !isController && !isRigCamera;
  88795. });
  88796. _this._descendants.forEach(function (node) {
  88797. node.parent = camera;
  88798. });
  88799. }
  88800. });
  88801. scene.onAfterCameraRenderObservable.add(function (camera) {
  88802. if (camera.parent === _this && _this.rigParenting) {
  88803. _this._descendants.forEach(function (node) {
  88804. node.parent = _this;
  88805. });
  88806. }
  88807. });
  88808. return _this;
  88809. }
  88810. /**
  88811. * Gets the device distance from the ground in meters.
  88812. * @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.
  88813. */
  88814. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  88815. if (this._standingMatrix) {
  88816. // Add standing matrix offset to get real offset from ground in room
  88817. this._standingMatrix.getTranslationToRef(this._workingVector);
  88818. return this._deviceRoomPosition.y + this._workingVector.y;
  88819. }
  88820. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  88821. return this._defaultHeight || 0;
  88822. };
  88823. /**
  88824. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88825. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  88826. */
  88827. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  88828. var _this = this;
  88829. if (callback === void 0) { callback = function (bool) { }; }
  88830. // Use standing matrix if available
  88831. this.getEngine().initWebVRAsync().then(function (result) {
  88832. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  88833. callback(false);
  88834. }
  88835. else {
  88836. _this._standingMatrix = new BABYLON.Matrix();
  88837. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  88838. if (!_this.getScene().useRightHandedSystem) {
  88839. [2, 6, 8, 9, 14].forEach(function (num) {
  88840. if (_this._standingMatrix) {
  88841. _this._standingMatrix.m[num] *= -1;
  88842. }
  88843. });
  88844. }
  88845. callback(true);
  88846. }
  88847. });
  88848. };
  88849. /**
  88850. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88851. * @returns A promise with a boolean set to if the standing matrix is supported.
  88852. */
  88853. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  88854. var _this = this;
  88855. return new Promise(function (res, rej) {
  88856. _this.useStandingMatrix(function (supported) {
  88857. res(supported);
  88858. });
  88859. });
  88860. };
  88861. /**
  88862. * Disposes the camera
  88863. */
  88864. WebVRFreeCamera.prototype.dispose = function () {
  88865. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  88866. _super.prototype.dispose.call(this);
  88867. };
  88868. /**
  88869. * Gets a vrController by name.
  88870. * @param name The name of the controller to retreive
  88871. * @returns the controller matching the name specified or null if not found
  88872. */
  88873. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  88874. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  88875. var gp = _a[_i];
  88876. if (gp.hand === name) {
  88877. return gp;
  88878. }
  88879. }
  88880. return null;
  88881. };
  88882. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  88883. /**
  88884. * The controller corrisponding to the users left hand.
  88885. */
  88886. get: function () {
  88887. if (!this._leftController) {
  88888. this._leftController = this.getControllerByName("left");
  88889. }
  88890. return this._leftController;
  88891. },
  88892. enumerable: true,
  88893. configurable: true
  88894. });
  88895. ;
  88896. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  88897. /**
  88898. * The controller corrisponding to the users right hand.
  88899. */
  88900. get: function () {
  88901. if (!this._rightController) {
  88902. this._rightController = this.getControllerByName("right");
  88903. }
  88904. return this._rightController;
  88905. },
  88906. enumerable: true,
  88907. configurable: true
  88908. });
  88909. ;
  88910. /**
  88911. * Casts a ray forward from the vrCamera's gaze.
  88912. * @param length Length of the ray (default: 100)
  88913. * @returns the ray corrisponding to the gaze
  88914. */
  88915. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  88916. if (length === void 0) { length = 100; }
  88917. if (this.leftCamera) {
  88918. // Use left eye to avoid computation to compute center on every call
  88919. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  88920. }
  88921. else {
  88922. return _super.prototype.getForwardRay.call(this, length);
  88923. }
  88924. };
  88925. /**
  88926. * Updates the camera based on device's frame data
  88927. */
  88928. WebVRFreeCamera.prototype._checkInputs = function () {
  88929. if (this._vrDevice && this._vrDevice.isPresenting) {
  88930. this._vrDevice.getFrameData(this._frameData);
  88931. this.updateFromDevice(this._frameData.pose);
  88932. }
  88933. _super.prototype._checkInputs.call(this);
  88934. };
  88935. /**
  88936. * Updates the poseControlled values based on the input device pose.
  88937. * @param poseData Pose coming from the device
  88938. */
  88939. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  88940. if (poseData && poseData.orientation) {
  88941. this.rawPose = poseData;
  88942. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  88943. if (this.getScene().useRightHandedSystem) {
  88944. this._deviceRoomRotationQuaternion.z *= -1;
  88945. this._deviceRoomRotationQuaternion.w *= -1;
  88946. }
  88947. if (this.webVROptions.trackPosition && this.rawPose.position) {
  88948. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  88949. if (this.getScene().useRightHandedSystem) {
  88950. this._deviceRoomPosition.z *= -1;
  88951. }
  88952. }
  88953. }
  88954. };
  88955. /**
  88956. * WebVR's attach control will start broadcasting frames to the device.
  88957. * Note that in certain browsers (chrome for example) this function must be called
  88958. * within a user-interaction callback. Example:
  88959. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  88960. *
  88961. * @param element html element to attach the vrDevice to
  88962. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  88963. */
  88964. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  88965. _super.prototype.attachControl.call(this, element, noPreventDefault);
  88966. this._attached = true;
  88967. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  88968. if (this._vrDevice) {
  88969. this.getEngine().enableVR();
  88970. }
  88971. };
  88972. /**
  88973. * Detaches the camera from the html element and disables VR
  88974. *
  88975. * @param element html element to detach from
  88976. */
  88977. WebVRFreeCamera.prototype.detachControl = function (element) {
  88978. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  88979. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  88980. _super.prototype.detachControl.call(this, element);
  88981. this._attached = false;
  88982. this.getEngine().disableVR();
  88983. };
  88984. /**
  88985. * @returns the name of this class
  88986. */
  88987. WebVRFreeCamera.prototype.getClassName = function () {
  88988. return "WebVRFreeCamera";
  88989. };
  88990. /**
  88991. * Calls resetPose on the vrDisplay
  88992. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  88993. */
  88994. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  88995. //uses the vrDisplay's "resetPose()".
  88996. //pitch and roll won't be affected.
  88997. this._vrDevice.resetPose();
  88998. };
  88999. /**
  89000. * Updates the rig cameras (left and right eye)
  89001. */
  89002. WebVRFreeCamera.prototype._updateRigCameras = function () {
  89003. var camLeft = this._rigCameras[0];
  89004. var camRight = this._rigCameras[1];
  89005. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89006. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  89007. camLeft.position.copyFrom(this._deviceRoomPosition);
  89008. camRight.position.copyFrom(this._deviceRoomPosition);
  89009. };
  89010. /**
  89011. * Updates the cached values of the camera
  89012. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  89013. */
  89014. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  89015. var _this = this;
  89016. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  89017. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  89018. if (!this.updateCacheCalled) {
  89019. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  89020. this.updateCacheCalled = true;
  89021. this.update();
  89022. }
  89023. // Set working vector to the device position in room space rotated by the new rotation
  89024. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  89025. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  89026. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  89027. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  89028. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  89029. // Add translation from anchor position
  89030. this._deviceToWorld.getTranslationToRef(this._workingVector);
  89031. this._workingVector.addInPlace(this.position);
  89032. this._workingVector.subtractInPlace(this._cache.position);
  89033. this._deviceToWorld.setTranslation(this._workingVector);
  89034. // Set an inverted matrix to be used when updating the camera
  89035. this._deviceToWorld.invertToRef(this._worldToDevice);
  89036. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  89037. this.controllers.forEach(function (controller) {
  89038. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  89039. controller.update();
  89040. });
  89041. }
  89042. if (!ignoreParentClass) {
  89043. _super.prototype._updateCache.call(this);
  89044. }
  89045. this.updateCacheCalled = false;
  89046. };
  89047. /**
  89048. * Updates the current device position and rotation in the babylon world
  89049. */
  89050. WebVRFreeCamera.prototype.update = function () {
  89051. // Get current device position in babylon world
  89052. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  89053. // Get current device rotation in babylon world
  89054. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  89055. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  89056. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  89057. _super.prototype.update.call(this);
  89058. };
  89059. /**
  89060. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  89061. * @returns an identity matrix
  89062. */
  89063. WebVRFreeCamera.prototype._getViewMatrix = function () {
  89064. return BABYLON.Matrix.Identity();
  89065. };
  89066. /**
  89067. * This function is called by the two RIG cameras.
  89068. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  89069. */
  89070. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  89071. var _this = this;
  89072. // Update the parent camera prior to using a child camera to avoid desynchronization
  89073. var parentCamera = this._cameraRigParams["parentCamera"];
  89074. parentCamera._updateCache();
  89075. //WebVR 1.1
  89076. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  89077. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  89078. if (!this.getScene().useRightHandedSystem) {
  89079. [2, 6, 8, 9, 14].forEach(function (num) {
  89080. _this._webvrViewMatrix.m[num] *= -1;
  89081. });
  89082. }
  89083. // update the camera rotation matrix
  89084. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  89085. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  89086. // Computing target and final matrix
  89087. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  89088. // should the view matrix be updated with scale and position offset?
  89089. if (parentCamera.deviceScaleFactor !== 1) {
  89090. this._webvrViewMatrix.invert();
  89091. // scale the position, if set
  89092. if (parentCamera.deviceScaleFactor) {
  89093. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  89094. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  89095. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  89096. }
  89097. this._webvrViewMatrix.invert();
  89098. }
  89099. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  89100. // Compute global position
  89101. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  89102. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  89103. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  89104. this._workingMatrix.getTranslationToRef(this._globalPosition);
  89105. this._markSyncedWithParent();
  89106. return this._webvrViewMatrix;
  89107. };
  89108. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  89109. var _this = this;
  89110. var parentCamera = this.parent;
  89111. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  89112. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  89113. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  89114. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  89115. //babylon compatible matrix
  89116. if (!this.getScene().useRightHandedSystem) {
  89117. [8, 9, 10, 11].forEach(function (num) {
  89118. _this._projectionMatrix.m[num] *= -1;
  89119. });
  89120. }
  89121. return this._projectionMatrix;
  89122. };
  89123. /**
  89124. * Initializes the controllers and their meshes
  89125. */
  89126. WebVRFreeCamera.prototype.initControllers = function () {
  89127. var _this = this;
  89128. this.controllers = [];
  89129. var manager = this.getScene().gamepadManager;
  89130. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  89131. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89132. var webVrController = gamepad;
  89133. if (webVrController.defaultModel) {
  89134. webVrController.defaultModel.setEnabled(false);
  89135. }
  89136. if (webVrController.hand === "right") {
  89137. _this._rightController = null;
  89138. }
  89139. if (webVrController.hand === "left") {
  89140. _this._leftController = null;
  89141. }
  89142. var controllerIndex = _this.controllers.indexOf(webVrController);
  89143. if (controllerIndex !== -1) {
  89144. _this.controllers.splice(controllerIndex, 1);
  89145. }
  89146. }
  89147. });
  89148. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  89149. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  89150. var webVrController_1 = gamepad;
  89151. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  89152. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  89153. if (_this.webVROptions.controllerMeshes) {
  89154. if (webVrController_1.defaultModel) {
  89155. webVrController_1.defaultModel.setEnabled(true);
  89156. }
  89157. else {
  89158. // Load the meshes
  89159. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  89160. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  89161. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  89162. if (_this.webVROptions.defaultLightingOnControllers) {
  89163. if (!_this._lightOnControllers) {
  89164. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  89165. }
  89166. var activateLightOnSubMeshes_1 = function (mesh, light) {
  89167. var children = mesh.getChildren();
  89168. if (children.length !== 0) {
  89169. children.forEach(function (mesh) {
  89170. light.includedOnlyMeshes.push(mesh);
  89171. activateLightOnSubMeshes_1(mesh, light);
  89172. });
  89173. }
  89174. };
  89175. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  89176. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  89177. }
  89178. });
  89179. }
  89180. }
  89181. webVrController_1.attachToPoseControlledCamera(_this);
  89182. // since this is async - sanity check. Is the controller already stored?
  89183. if (_this.controllers.indexOf(webVrController_1) === -1) {
  89184. //add to the controllers array
  89185. _this.controllers.push(webVrController_1);
  89186. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  89187. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  89188. // So we're overriding setting left & right manually to be sure
  89189. var firstViveWandDetected = false;
  89190. for (var i = 0; i < _this.controllers.length; i++) {
  89191. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89192. if (!firstViveWandDetected) {
  89193. firstViveWandDetected = true;
  89194. _this.controllers[i].hand = "left";
  89195. }
  89196. else {
  89197. _this.controllers[i].hand = "right";
  89198. }
  89199. }
  89200. }
  89201. //did we find enough controllers? Great! let the developer know.
  89202. if (_this.controllers.length >= 2) {
  89203. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  89204. }
  89205. }
  89206. }
  89207. });
  89208. };
  89209. return WebVRFreeCamera;
  89210. }(BABYLON.FreeCamera));
  89211. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  89212. })(BABYLON || (BABYLON = {}));
  89213. //# sourceMappingURL=babylon.webVRCamera.js.map
  89214. var BABYLON;
  89215. (function (BABYLON) {
  89216. // We're mainly based on the logic defined into the FreeCamera code
  89217. /**
  89218. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  89219. * being tilted forward or back and left or right.
  89220. */
  89221. var DeviceOrientationCamera = /** @class */ (function (_super) {
  89222. __extends(DeviceOrientationCamera, _super);
  89223. /**
  89224. * Creates a new device orientation camera
  89225. * @param name The name of the camera
  89226. * @param position The start position camera
  89227. * @param scene The scene the camera belongs to
  89228. */
  89229. function DeviceOrientationCamera(name, position, scene) {
  89230. var _this = _super.call(this, name, position, scene) || this;
  89231. _this._quaternionCache = new BABYLON.Quaternion();
  89232. _this.inputs.addDeviceOrientation();
  89233. return _this;
  89234. }
  89235. /**
  89236. * Gets the current instance class name ("DeviceOrientationCamera").
  89237. * This helps avoiding instanceof at run time.
  89238. * @returns the class name
  89239. */
  89240. DeviceOrientationCamera.prototype.getClassName = function () {
  89241. return "DeviceOrientationCamera";
  89242. };
  89243. /**
  89244. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  89245. */
  89246. DeviceOrientationCamera.prototype._checkInputs = function () {
  89247. _super.prototype._checkInputs.call(this);
  89248. this._quaternionCache.copyFrom(this.rotationQuaternion);
  89249. if (this._initialQuaternion) {
  89250. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89251. }
  89252. };
  89253. /**
  89254. * Reset the camera to its default orientation on the specified axis only.
  89255. * @param axis The axis to reset
  89256. */
  89257. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  89258. var _this = this;
  89259. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  89260. //can only work if this camera has a rotation quaternion already.
  89261. if (!this.rotationQuaternion)
  89262. return;
  89263. if (!this._initialQuaternion) {
  89264. this._initialQuaternion = new BABYLON.Quaternion();
  89265. }
  89266. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  89267. ['x', 'y', 'z'].forEach(function (axisName) {
  89268. if (!axis[axisName]) {
  89269. _this._initialQuaternion[axisName] = 0;
  89270. }
  89271. else {
  89272. _this._initialQuaternion[axisName] *= -1;
  89273. }
  89274. });
  89275. this._initialQuaternion.normalize();
  89276. //force rotation update
  89277. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  89278. };
  89279. return DeviceOrientationCamera;
  89280. }(BABYLON.FreeCamera));
  89281. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  89282. })(BABYLON || (BABYLON = {}));
  89283. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  89284. var BABYLON;
  89285. (function (BABYLON) {
  89286. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  89287. __extends(VRDeviceOrientationFreeCamera, _super);
  89288. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89289. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89290. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89291. var _this = _super.call(this, name, position, scene) || this;
  89292. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89293. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89294. return _this;
  89295. }
  89296. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  89297. return "VRDeviceOrientationFreeCamera";
  89298. };
  89299. return VRDeviceOrientationFreeCamera;
  89300. }(BABYLON.DeviceOrientationCamera));
  89301. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  89302. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  89303. __extends(VRDeviceOrientationGamepadCamera, _super);
  89304. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  89305. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89306. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89307. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  89308. _this.inputs.addGamepad();
  89309. return _this;
  89310. }
  89311. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  89312. return "VRDeviceOrientationGamepadCamera";
  89313. };
  89314. return VRDeviceOrientationGamepadCamera;
  89315. }(VRDeviceOrientationFreeCamera));
  89316. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  89317. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  89318. __extends(VRDeviceOrientationArcRotateCamera, _super);
  89319. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  89320. if (compensateDistortion === void 0) { compensateDistortion = true; }
  89321. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  89322. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89323. vrCameraMetrics.compensateDistortion = compensateDistortion;
  89324. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  89325. _this.inputs.addVRDeviceOrientation();
  89326. return _this;
  89327. }
  89328. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  89329. return "VRDeviceOrientationArcRotateCamera";
  89330. };
  89331. return VRDeviceOrientationArcRotateCamera;
  89332. }(BABYLON.ArcRotateCamera));
  89333. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  89334. })(BABYLON || (BABYLON = {}));
  89335. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  89336. var BABYLON;
  89337. (function (BABYLON) {
  89338. /**
  89339. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  89340. */
  89341. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  89342. __extends(AnaglyphFreeCamera, _super);
  89343. /**
  89344. * Creates a new AnaglyphFreeCamera
  89345. * @param name defines camera name
  89346. * @param position defines initial position
  89347. * @param interaxialDistance defines distance between each color axis
  89348. * @param scene defines the hosting scene
  89349. */
  89350. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  89351. var _this = _super.call(this, name, position, scene) || this;
  89352. _this.interaxialDistance = interaxialDistance;
  89353. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89354. return _this;
  89355. }
  89356. /**
  89357. * Gets camera class name
  89358. * @returns AnaglyphFreeCamera
  89359. */
  89360. AnaglyphFreeCamera.prototype.getClassName = function () {
  89361. return "AnaglyphFreeCamera";
  89362. };
  89363. return AnaglyphFreeCamera;
  89364. }(BABYLON.FreeCamera));
  89365. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  89366. /**
  89367. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  89368. */
  89369. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  89370. __extends(AnaglyphArcRotateCamera, _super);
  89371. /**
  89372. * Creates a new AnaglyphArcRotateCamera
  89373. * @param name defines camera name
  89374. * @param alpha defines alpha angle (in radians)
  89375. * @param beta defines beta angle (in radians)
  89376. * @param radius defines radius
  89377. * @param target defines camera target
  89378. * @param interaxialDistance defines distance between each color axis
  89379. * @param scene defines the hosting scene
  89380. */
  89381. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  89382. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89383. _this.interaxialDistance = interaxialDistance;
  89384. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89385. return _this;
  89386. }
  89387. /**
  89388. * Gets camera class name
  89389. * @returns AnaglyphArcRotateCamera
  89390. */
  89391. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  89392. return "AnaglyphArcRotateCamera";
  89393. };
  89394. return AnaglyphArcRotateCamera;
  89395. }(BABYLON.ArcRotateCamera));
  89396. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  89397. /**
  89398. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  89399. */
  89400. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  89401. __extends(AnaglyphGamepadCamera, _super);
  89402. /**
  89403. * Creates a new AnaglyphGamepadCamera
  89404. * @param name defines camera name
  89405. * @param position defines initial position
  89406. * @param interaxialDistance defines distance between each color axis
  89407. * @param scene defines the hosting scene
  89408. */
  89409. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  89410. var _this = _super.call(this, name, position, scene) || this;
  89411. _this.interaxialDistance = interaxialDistance;
  89412. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89413. return _this;
  89414. }
  89415. /**
  89416. * Gets camera class name
  89417. * @returns AnaglyphGamepadCamera
  89418. */
  89419. AnaglyphGamepadCamera.prototype.getClassName = function () {
  89420. return "AnaglyphGamepadCamera";
  89421. };
  89422. return AnaglyphGamepadCamera;
  89423. }(BABYLON.GamepadCamera));
  89424. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  89425. /**
  89426. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  89427. */
  89428. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  89429. __extends(AnaglyphUniversalCamera, _super);
  89430. /**
  89431. * Creates a new AnaglyphUniversalCamera
  89432. * @param name defines camera name
  89433. * @param position defines initial position
  89434. * @param interaxialDistance defines distance between each color axis
  89435. * @param scene defines the hosting scene
  89436. */
  89437. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  89438. var _this = _super.call(this, name, position, scene) || this;
  89439. _this.interaxialDistance = interaxialDistance;
  89440. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  89441. return _this;
  89442. }
  89443. /**
  89444. * Gets camera class name
  89445. * @returns AnaglyphUniversalCamera
  89446. */
  89447. AnaglyphUniversalCamera.prototype.getClassName = function () {
  89448. return "AnaglyphUniversalCamera";
  89449. };
  89450. return AnaglyphUniversalCamera;
  89451. }(BABYLON.UniversalCamera));
  89452. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  89453. /**
  89454. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  89455. */
  89456. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  89457. __extends(StereoscopicFreeCamera, _super);
  89458. /**
  89459. * Creates a new StereoscopicFreeCamera
  89460. * @param name defines camera name
  89461. * @param position defines initial position
  89462. * @param interaxialDistance defines distance between each color axis
  89463. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89464. * @param scene defines the hosting scene
  89465. */
  89466. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89467. var _this = _super.call(this, name, position, scene) || this;
  89468. _this.interaxialDistance = interaxialDistance;
  89469. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89470. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89471. return _this;
  89472. }
  89473. /**
  89474. * Gets camera class name
  89475. * @returns StereoscopicFreeCamera
  89476. */
  89477. StereoscopicFreeCamera.prototype.getClassName = function () {
  89478. return "StereoscopicFreeCamera";
  89479. };
  89480. return StereoscopicFreeCamera;
  89481. }(BABYLON.FreeCamera));
  89482. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  89483. /**
  89484. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  89485. */
  89486. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  89487. __extends(StereoscopicArcRotateCamera, _super);
  89488. /**
  89489. * Creates a new StereoscopicArcRotateCamera
  89490. * @param name defines camera name
  89491. * @param alpha defines alpha angle (in radians)
  89492. * @param beta defines beta angle (in radians)
  89493. * @param radius defines radius
  89494. * @param target defines camera target
  89495. * @param interaxialDistance defines distance between each color axis
  89496. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89497. * @param scene defines the hosting scene
  89498. */
  89499. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  89500. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  89501. _this.interaxialDistance = interaxialDistance;
  89502. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89503. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89504. return _this;
  89505. }
  89506. /**
  89507. * Gets camera class name
  89508. * @returns StereoscopicArcRotateCamera
  89509. */
  89510. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  89511. return "StereoscopicArcRotateCamera";
  89512. };
  89513. return StereoscopicArcRotateCamera;
  89514. }(BABYLON.ArcRotateCamera));
  89515. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  89516. /**
  89517. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  89518. */
  89519. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  89520. __extends(StereoscopicGamepadCamera, _super);
  89521. /**
  89522. * Creates a new StereoscopicGamepadCamera
  89523. * @param name defines camera name
  89524. * @param position defines initial position
  89525. * @param interaxialDistance defines distance between each color axis
  89526. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89527. * @param scene defines the hosting scene
  89528. */
  89529. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89530. var _this = _super.call(this, name, position, scene) || this;
  89531. _this.interaxialDistance = interaxialDistance;
  89532. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89533. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89534. return _this;
  89535. }
  89536. /**
  89537. * Gets camera class name
  89538. * @returns StereoscopicGamepadCamera
  89539. */
  89540. StereoscopicGamepadCamera.prototype.getClassName = function () {
  89541. return "StereoscopicGamepadCamera";
  89542. };
  89543. return StereoscopicGamepadCamera;
  89544. }(BABYLON.GamepadCamera));
  89545. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  89546. /**
  89547. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  89548. */
  89549. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  89550. __extends(StereoscopicUniversalCamera, _super);
  89551. /**
  89552. * Creates a new StereoscopicUniversalCamera
  89553. * @param name defines camera name
  89554. * @param position defines initial position
  89555. * @param interaxialDistance defines distance between each color axis
  89556. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  89557. * @param scene defines the hosting scene
  89558. */
  89559. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  89560. var _this = _super.call(this, name, position, scene) || this;
  89561. _this.interaxialDistance = interaxialDistance;
  89562. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  89563. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  89564. return _this;
  89565. }
  89566. /**
  89567. * Gets camera class name
  89568. * @returns StereoscopicUniversalCamera
  89569. */
  89570. StereoscopicUniversalCamera.prototype.getClassName = function () {
  89571. return "StereoscopicUniversalCamera";
  89572. };
  89573. return StereoscopicUniversalCamera;
  89574. }(BABYLON.UniversalCamera));
  89575. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  89576. })(BABYLON || (BABYLON = {}));
  89577. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  89578. var BABYLON;
  89579. (function (BABYLON) {
  89580. var VRExperienceHelperGazer = /** @class */ (function () {
  89581. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  89582. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  89583. this.scene = scene;
  89584. this._pointerDownOnMeshAsked = false;
  89585. this._isActionableMesh = false;
  89586. this._teleportationRequestInitiated = false;
  89587. this._teleportationBackRequestInitiated = false;
  89588. this._rotationRightAsked = false;
  89589. this._rotationLeftAsked = false;
  89590. this._dpadPressed = true;
  89591. this._activePointer = false;
  89592. this._id = VRExperienceHelperGazer._idCounter++;
  89593. // Gaze tracker
  89594. if (!gazeTrackerToClone) {
  89595. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  89596. this._gazeTracker.bakeCurrentTransformIntoVertices();
  89597. this._gazeTracker.isPickable = false;
  89598. this._gazeTracker.isVisible = false;
  89599. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  89600. targetMat.specularColor = BABYLON.Color3.Black();
  89601. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89602. targetMat.backFaceCulling = false;
  89603. this._gazeTracker.material = targetMat;
  89604. }
  89605. else {
  89606. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  89607. }
  89608. }
  89609. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  89610. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  89611. };
  89612. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  89613. this._pointerDownOnMeshAsked = true;
  89614. if (this._currentHit) {
  89615. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  89616. }
  89617. };
  89618. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  89619. if (this._currentHit) {
  89620. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  89621. }
  89622. this._pointerDownOnMeshAsked = false;
  89623. };
  89624. VRExperienceHelperGazer.prototype._activatePointer = function () {
  89625. this._activePointer = true;
  89626. };
  89627. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  89628. this._activePointer = false;
  89629. };
  89630. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  89631. if (distance === void 0) { distance = 100; }
  89632. };
  89633. VRExperienceHelperGazer.prototype.dispose = function () {
  89634. this._interactionsEnabled = false;
  89635. this._teleportationEnabled = false;
  89636. if (this._gazeTracker) {
  89637. this._gazeTracker.dispose();
  89638. }
  89639. };
  89640. VRExperienceHelperGazer._idCounter = 0;
  89641. return VRExperienceHelperGazer;
  89642. }());
  89643. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  89644. __extends(VRExperienceHelperControllerGazer, _super);
  89645. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  89646. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  89647. _this.webVRController = webVRController;
  89648. // Laser pointer
  89649. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  89650. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  89651. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89652. laserPointerMaterial.alpha = 0.6;
  89653. _this._laserPointer.material = laserPointerMaterial;
  89654. _this._laserPointer.rotation.x = Math.PI / 2;
  89655. _this._laserPointer.position.z = -0.5;
  89656. _this._laserPointer.isVisible = false;
  89657. if (!webVRController.mesh) {
  89658. // Create an empty mesh that is used prior to loading the high quality model
  89659. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  89660. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  89661. preloadPointerPose.rotation.x = -0.7;
  89662. preloadMesh.addChild(preloadPointerPose);
  89663. webVRController.attachToMesh(preloadMesh);
  89664. }
  89665. _this._setLaserPointerParent(webVRController.mesh);
  89666. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  89667. _this._setLaserPointerParent(mesh);
  89668. });
  89669. return _this;
  89670. }
  89671. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  89672. return this.webVRController.getForwardRay(length);
  89673. };
  89674. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  89675. _super.prototype._activatePointer.call(this);
  89676. this._laserPointer.isVisible = true;
  89677. };
  89678. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  89679. _super.prototype._deactivatePointer.call(this);
  89680. this._laserPointer.isVisible = false;
  89681. };
  89682. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  89683. this._laserPointer.material.emissiveColor = color;
  89684. };
  89685. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  89686. var makeNotPick = function (root) {
  89687. root.name += " laserPointer";
  89688. root.getChildMeshes().forEach(function (c) {
  89689. makeNotPick(c);
  89690. });
  89691. };
  89692. makeNotPick(mesh);
  89693. var childMeshes = mesh.getChildMeshes();
  89694. this.webVRController._pointingPoseNode = null;
  89695. for (var i = 0; i < childMeshes.length; i++) {
  89696. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  89697. mesh = childMeshes[i];
  89698. this.webVRController._pointingPoseNode = mesh;
  89699. break;
  89700. }
  89701. }
  89702. this._laserPointer.parent = mesh;
  89703. };
  89704. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  89705. if (distance === void 0) { distance = 100; }
  89706. this._laserPointer.scaling.y = distance;
  89707. this._laserPointer.position.z = -distance / 2;
  89708. };
  89709. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  89710. _super.prototype.dispose.call(this);
  89711. this._laserPointer.dispose();
  89712. if (this._meshAttachedObserver) {
  89713. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  89714. }
  89715. };
  89716. return VRExperienceHelperControllerGazer;
  89717. }(VRExperienceHelperGazer));
  89718. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  89719. __extends(VRExperienceHelperCameraGazer, _super);
  89720. function VRExperienceHelperCameraGazer(getCamera, scene) {
  89721. var _this = _super.call(this, scene) || this;
  89722. _this.getCamera = getCamera;
  89723. return _this;
  89724. }
  89725. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  89726. var camera = this.getCamera();
  89727. if (camera) {
  89728. return camera.getForwardRay(length);
  89729. }
  89730. else {
  89731. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  89732. }
  89733. };
  89734. return VRExperienceHelperCameraGazer;
  89735. }(VRExperienceHelperGazer));
  89736. /**
  89737. * Helps to quickly add VR support to an existing scene.
  89738. * See http://doc.babylonjs.com/how_to/webvr_helper
  89739. */
  89740. var VRExperienceHelper = /** @class */ (function () {
  89741. /**
  89742. * Instantiates a VRExperienceHelper.
  89743. * Helps to quickly add VR support to an existing scene.
  89744. * @param scene The scene the VRExperienceHelper belongs to.
  89745. * @param webVROptions Options to modify the vr experience helper's behavior.
  89746. */
  89747. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  89748. if (webVROptions === void 0) { webVROptions = {}; }
  89749. var _this = this;
  89750. this.webVROptions = webVROptions;
  89751. // Can the system support WebVR, even if a headset isn't plugged in?
  89752. this._webVRsupported = false;
  89753. // If WebVR is supported, is a headset plugged in and are we ready to present?
  89754. this._webVRready = false;
  89755. // Are we waiting for the requestPresent callback to complete?
  89756. this._webVRrequesting = false;
  89757. // Are we presenting to the headset right now?
  89758. this._webVRpresenting = false;
  89759. // Are we presenting in the fullscreen fallback?
  89760. this._fullscreenVRpresenting = false;
  89761. /**
  89762. * Observable raised when entering VR.
  89763. */
  89764. this.onEnteringVRObservable = new BABYLON.Observable();
  89765. /**
  89766. * Observable raised when exiting VR.
  89767. */
  89768. this.onExitingVRObservable = new BABYLON.Observable();
  89769. /**
  89770. * Observable raised when controller mesh is loaded.
  89771. */
  89772. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89773. this._useCustomVRButton = false;
  89774. this._teleportationRequested = false;
  89775. this._teleportActive = false;
  89776. this._floorMeshesCollection = [];
  89777. this._rotationAllowed = true;
  89778. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  89779. this._isDefaultTeleportationTarget = true;
  89780. this._teleportationFillColor = "#444444";
  89781. this._teleportationBorderColor = "#FFFFFF";
  89782. this._rotationAngle = 0;
  89783. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  89784. this._padSensibilityUp = 0.65;
  89785. this._padSensibilityDown = 0.35;
  89786. this.leftController = null;
  89787. this.rightController = null;
  89788. /**
  89789. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  89790. */
  89791. this.onNewMeshSelected = new BABYLON.Observable();
  89792. /**
  89793. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  89794. */
  89795. this.onNewMeshPicked = new BABYLON.Observable();
  89796. /**
  89797. * Observable raised before camera teleportation
  89798. */
  89799. this.onBeforeCameraTeleport = new BABYLON.Observable();
  89800. /**
  89801. * Observable raised after camera teleportation
  89802. */
  89803. this.onAfterCameraTeleport = new BABYLON.Observable();
  89804. /**
  89805. * Observable raised when current selected mesh gets unselected
  89806. */
  89807. this.onSelectedMeshUnselected = new BABYLON.Observable();
  89808. /**
  89809. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  89810. */
  89811. this.teleportationEnabled = true;
  89812. this._teleportationInitialized = false;
  89813. this._interactionsEnabled = false;
  89814. this._interactionsRequested = false;
  89815. this._displayGaze = true;
  89816. this._displayLaserPointer = true;
  89817. this._onResize = function () {
  89818. _this.moveButtonToBottomRight();
  89819. if (_this._fullscreenVRpresenting && _this._webVRready) {
  89820. _this.exitVR();
  89821. }
  89822. };
  89823. this._onFullscreenChange = function () {
  89824. if (document.fullscreen !== undefined) {
  89825. _this._fullscreenVRpresenting = document.fullscreen;
  89826. }
  89827. else if (document.mozFullScreen !== undefined) {
  89828. _this._fullscreenVRpresenting = document.mozFullScreen;
  89829. }
  89830. else if (document.webkitIsFullScreen !== undefined) {
  89831. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  89832. }
  89833. else if (document.msIsFullScreen !== undefined) {
  89834. _this._fullscreenVRpresenting = document.msIsFullScreen;
  89835. }
  89836. if (!_this._fullscreenVRpresenting && _this._canvas) {
  89837. _this.exitVR();
  89838. if (!_this._useCustomVRButton) {
  89839. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  89840. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  89841. }
  89842. }
  89843. };
  89844. this.beforeRender = function () {
  89845. if (_this.leftController && _this.leftController._activePointer) {
  89846. _this._castRayAndSelectObject(_this.leftController);
  89847. }
  89848. if (_this.rightController && _this.rightController._activePointer) {
  89849. _this._castRayAndSelectObject(_this.rightController);
  89850. }
  89851. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  89852. _this._castRayAndSelectObject(_this._cameraGazer);
  89853. }
  89854. else {
  89855. _this._cameraGazer._gazeTracker.isVisible = false;
  89856. }
  89857. };
  89858. this._onNewGamepadConnected = function (gamepad) {
  89859. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  89860. if (gamepad.leftStick) {
  89861. gamepad.onleftstickchanged(function (stickValues) {
  89862. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  89863. // Listening to classic/xbox gamepad only if no VR controller is active
  89864. if ((!_this.leftController && !_this.rightController) ||
  89865. ((_this.leftController && !_this.leftController._activePointer) &&
  89866. (_this.rightController && !_this.rightController._activePointer))) {
  89867. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  89868. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  89869. }
  89870. }
  89871. });
  89872. }
  89873. if (gamepad.rightStick) {
  89874. gamepad.onrightstickchanged(function (stickValues) {
  89875. if (_this._teleportationInitialized) {
  89876. _this._checkRotate(stickValues, _this._cameraGazer);
  89877. }
  89878. });
  89879. }
  89880. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  89881. gamepad.onbuttondown(function (buttonPressed) {
  89882. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89883. _this._cameraGazer._selectionPointerDown();
  89884. }
  89885. });
  89886. gamepad.onbuttonup(function (buttonPressed) {
  89887. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89888. _this._cameraGazer._selectionPointerUp();
  89889. }
  89890. });
  89891. }
  89892. }
  89893. else {
  89894. var webVRController = gamepad;
  89895. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  89896. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  89897. _this.rightController = controller;
  89898. }
  89899. else {
  89900. _this.leftController = controller;
  89901. }
  89902. _this._tryEnableInteractionOnController(controller);
  89903. }
  89904. };
  89905. // 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
  89906. this._tryEnableInteractionOnController = function (controller) {
  89907. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  89908. _this._enableInteractionOnController(controller);
  89909. }
  89910. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  89911. _this._enableTeleportationOnController(controller);
  89912. }
  89913. };
  89914. this._onNewGamepadDisconnected = function (gamepad) {
  89915. if (gamepad instanceof BABYLON.WebVRController) {
  89916. if (gamepad.hand === "left" && _this.leftController != null) {
  89917. _this.leftController.dispose();
  89918. _this.leftController = null;
  89919. }
  89920. if (gamepad.hand === "right" && _this.rightController != null) {
  89921. _this.rightController.dispose();
  89922. _this.rightController = null;
  89923. }
  89924. }
  89925. };
  89926. this._workingVector = BABYLON.Vector3.Zero();
  89927. this._workingQuaternion = BABYLON.Quaternion.Identity();
  89928. this._workingMatrix = BABYLON.Matrix.Identity();
  89929. this._scene = scene;
  89930. this._canvas = scene.getEngine().getRenderingCanvas();
  89931. // Parse options
  89932. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  89933. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  89934. }
  89935. if (webVROptions.createDeviceOrientationCamera === undefined) {
  89936. webVROptions.createDeviceOrientationCamera = true;
  89937. }
  89938. if (webVROptions.laserToggle === undefined) {
  89939. webVROptions.laserToggle = true;
  89940. }
  89941. if (webVROptions.defaultHeight === undefined) {
  89942. webVROptions.defaultHeight = 1.7;
  89943. }
  89944. if (webVROptions.useCustomVRButton) {
  89945. this._useCustomVRButton = true;
  89946. if (webVROptions.customVRButton) {
  89947. this._btnVR = webVROptions.customVRButton;
  89948. }
  89949. }
  89950. if (webVROptions.rayLength) {
  89951. this._rayLength = webVROptions.rayLength;
  89952. }
  89953. this._defaultHeight = webVROptions.defaultHeight;
  89954. if (webVROptions.positionScale) {
  89955. this._rayLength *= webVROptions.positionScale;
  89956. this._defaultHeight *= webVROptions.positionScale;
  89957. }
  89958. // Set position
  89959. if (this._scene.activeCamera) {
  89960. this._position = this._scene.activeCamera.position.clone();
  89961. }
  89962. else {
  89963. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  89964. }
  89965. // Set non-vr camera
  89966. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  89967. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  89968. // Copy data from existing camera
  89969. if (this._scene.activeCamera) {
  89970. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  89971. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  89972. // Set rotation from previous camera
  89973. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  89974. var targetCamera = this._scene.activeCamera;
  89975. if (targetCamera.rotationQuaternion) {
  89976. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  89977. }
  89978. else {
  89979. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  89980. }
  89981. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  89982. }
  89983. }
  89984. this._scene.activeCamera = this._deviceOrientationCamera;
  89985. if (this._canvas) {
  89986. this._scene.activeCamera.attachControl(this._canvas);
  89987. }
  89988. }
  89989. else {
  89990. this._existingCamera = this._scene.activeCamera;
  89991. }
  89992. // Create VR cameras
  89993. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  89994. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  89995. }
  89996. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  89997. this._webVRCamera.useStandingMatrix();
  89998. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  89999. // Create default button
  90000. if (!this._useCustomVRButton) {
  90001. this._btnVR = document.createElement("BUTTON");
  90002. this._btnVR.className = "babylonVRicon";
  90003. this._btnVR.id = "babylonVRiconbtn";
  90004. this._btnVR.title = "Click to switch to VR";
  90005. 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) }";
  90006. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  90007. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  90008. // css += ".babylonVRicon.vrdisplaysupported { }";
  90009. // css += ".babylonVRicon.vrdisplayready { }";
  90010. // css += ".babylonVRicon.vrdisplayrequesting { }";
  90011. var style = document.createElement('style');
  90012. style.appendChild(document.createTextNode(css));
  90013. document.getElementsByTagName('head')[0].appendChild(style);
  90014. this.moveButtonToBottomRight();
  90015. }
  90016. // VR button click event
  90017. if (this._btnVR) {
  90018. this._btnVR.addEventListener("click", function () {
  90019. if (!_this.isInVRMode) {
  90020. _this.enterVR();
  90021. }
  90022. else {
  90023. _this.exitVR();
  90024. }
  90025. });
  90026. }
  90027. // Window events
  90028. window.addEventListener("resize", this._onResize);
  90029. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  90030. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  90031. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  90032. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  90033. // Display vr button when headset is connected
  90034. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  90035. this.displayVRButton();
  90036. }
  90037. else {
  90038. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  90039. if (e.vrDisplay) {
  90040. _this.displayVRButton();
  90041. }
  90042. });
  90043. }
  90044. // Exiting VR mode using 'ESC' key on desktop
  90045. this._onKeyDown = function (event) {
  90046. if (event.keyCode === 27 && _this.isInVRMode) {
  90047. _this.exitVR();
  90048. }
  90049. };
  90050. document.addEventListener("keydown", this._onKeyDown);
  90051. // Exiting VR mode double tapping the touch screen
  90052. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  90053. if (_this.isInVRMode) {
  90054. _this.exitVR();
  90055. if (_this._fullscreenVRpresenting) {
  90056. _this._scene.getEngine().switchFullscreen(true);
  90057. }
  90058. }
  90059. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  90060. // Listen for WebVR display changes
  90061. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  90062. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  90063. this._onVRRequestPresentStart = function () {
  90064. _this._webVRrequesting = true;
  90065. _this.updateButtonVisibility();
  90066. };
  90067. this._onVRRequestPresentComplete = function (success) {
  90068. _this._webVRrequesting = false;
  90069. _this.updateButtonVisibility();
  90070. };
  90071. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  90072. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  90073. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  90074. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90075. scene.onDisposeObservable.add(function () {
  90076. _this.dispose();
  90077. });
  90078. // Gamepad connection events
  90079. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  90080. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  90081. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  90082. this.updateButtonVisibility();
  90083. //create easing functions
  90084. this._circleEase = new BABYLON.CircleEase();
  90085. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90086. if (this.webVROptions.floorMeshes) {
  90087. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  90088. }
  90089. }
  90090. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  90091. /** Return this.onEnteringVRObservable
  90092. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  90093. */
  90094. get: function () {
  90095. return this.onEnteringVRObservable;
  90096. },
  90097. enumerable: true,
  90098. configurable: true
  90099. });
  90100. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  90101. /** Return this.onExitingVRObservable
  90102. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  90103. */
  90104. get: function () {
  90105. return this.onExitingVRObservable;
  90106. },
  90107. enumerable: true,
  90108. configurable: true
  90109. });
  90110. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  90111. /** Return this.onControllerMeshLoadedObservable
  90112. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  90113. */
  90114. get: function () {
  90115. return this.onControllerMeshLoadedObservable;
  90116. },
  90117. enumerable: true,
  90118. configurable: true
  90119. });
  90120. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  90121. /**
  90122. * The mesh used to display where the user is going to teleport.
  90123. */
  90124. get: function () {
  90125. return this._teleportationTarget;
  90126. },
  90127. /**
  90128. * Sets the mesh to be used to display where the user is going to teleport.
  90129. */
  90130. set: function (value) {
  90131. if (value) {
  90132. value.name = "teleportationTarget";
  90133. this._isDefaultTeleportationTarget = false;
  90134. this._teleportationTarget = value;
  90135. }
  90136. },
  90137. enumerable: true,
  90138. configurable: true
  90139. });
  90140. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  90141. /**
  90142. * The mesh used to display where the user is selecting,
  90143. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  90144. * See http://doc.babylonjs.com/resources/baking_transformations
  90145. */
  90146. get: function () {
  90147. return this._cameraGazer._gazeTracker;
  90148. },
  90149. set: function (value) {
  90150. if (value) {
  90151. this._cameraGazer._gazeTracker = value;
  90152. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  90153. this._cameraGazer._gazeTracker.isPickable = false;
  90154. this._cameraGazer._gazeTracker.isVisible = false;
  90155. this._cameraGazer._gazeTracker.name = "gazeTracker";
  90156. if (this.leftController) {
  90157. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90158. }
  90159. if (this.rightController) {
  90160. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  90161. }
  90162. }
  90163. },
  90164. enumerable: true,
  90165. configurable: true
  90166. });
  90167. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  90168. /**
  90169. * If the ray of the gaze should be displayed.
  90170. */
  90171. get: function () {
  90172. return this._displayGaze;
  90173. },
  90174. /**
  90175. * Sets if the ray of the gaze should be displayed.
  90176. */
  90177. set: function (value) {
  90178. this._displayGaze = value;
  90179. if (!value) {
  90180. this._cameraGazer._gazeTracker.isVisible = false;
  90181. if (this.leftController) {
  90182. this.leftController._gazeTracker.isVisible = false;
  90183. }
  90184. if (this.rightController) {
  90185. this.rightController._gazeTracker.isVisible = false;
  90186. }
  90187. }
  90188. },
  90189. enumerable: true,
  90190. configurable: true
  90191. });
  90192. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  90193. /**
  90194. * If the ray of the LaserPointer should be displayed.
  90195. */
  90196. get: function () {
  90197. return this._displayLaserPointer;
  90198. },
  90199. /**
  90200. * Sets if the ray of the LaserPointer should be displayed.
  90201. */
  90202. set: function (value) {
  90203. this._displayLaserPointer = value;
  90204. if (!value) {
  90205. if (this.rightController) {
  90206. this.rightController._deactivatePointer();
  90207. this.rightController._gazeTracker.isVisible = false;
  90208. }
  90209. if (this.leftController) {
  90210. this.leftController._deactivatePointer();
  90211. this.leftController._gazeTracker.isVisible = false;
  90212. }
  90213. }
  90214. else {
  90215. if (this.rightController) {
  90216. this.rightController._activatePointer();
  90217. }
  90218. if (this.leftController) {
  90219. this.leftController._activatePointer();
  90220. }
  90221. }
  90222. },
  90223. enumerable: true,
  90224. configurable: true
  90225. });
  90226. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  90227. /**
  90228. * The deviceOrientationCamera used as the camera when not in VR.
  90229. */
  90230. get: function () {
  90231. return this._deviceOrientationCamera;
  90232. },
  90233. enumerable: true,
  90234. configurable: true
  90235. });
  90236. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  90237. /**
  90238. * Based on the current WebVR support, returns the current VR camera used.
  90239. */
  90240. get: function () {
  90241. if (this._webVRready) {
  90242. return this._webVRCamera;
  90243. }
  90244. else {
  90245. return this._scene.activeCamera;
  90246. }
  90247. },
  90248. enumerable: true,
  90249. configurable: true
  90250. });
  90251. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  90252. /**
  90253. * The webVRCamera which is used when in VR.
  90254. */
  90255. get: function () {
  90256. return this._webVRCamera;
  90257. },
  90258. enumerable: true,
  90259. configurable: true
  90260. });
  90261. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  90262. /**
  90263. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  90264. */
  90265. get: function () {
  90266. return this._vrDeviceOrientationCamera;
  90267. },
  90268. enumerable: true,
  90269. configurable: true
  90270. });
  90271. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  90272. get: function () {
  90273. var result = this._cameraGazer._teleportationRequestInitiated
  90274. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  90275. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  90276. return result;
  90277. },
  90278. enumerable: true,
  90279. configurable: true
  90280. });
  90281. // Raised when one of the controller has loaded successfully its associated default mesh
  90282. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  90283. if (this.leftController && this.leftController.webVRController == webVRController) {
  90284. if (webVRController.mesh) {
  90285. this.leftController._setLaserPointerParent(webVRController.mesh);
  90286. }
  90287. }
  90288. if (this.rightController && this.rightController.webVRController == webVRController) {
  90289. if (webVRController.mesh) {
  90290. this.rightController._setLaserPointerParent(webVRController.mesh);
  90291. }
  90292. }
  90293. try {
  90294. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  90295. }
  90296. catch (err) {
  90297. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  90298. }
  90299. };
  90300. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  90301. /**
  90302. * Gets a value indicating if we are currently in VR mode.
  90303. */
  90304. get: function () {
  90305. return this._webVRpresenting || this._fullscreenVRpresenting;
  90306. },
  90307. enumerable: true,
  90308. configurable: true
  90309. });
  90310. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  90311. var vrDisplay = this._scene.getEngine().getVRDevice();
  90312. if (vrDisplay) {
  90313. var wasPresenting = this._webVRpresenting;
  90314. // A VR display is connected
  90315. this._webVRpresenting = vrDisplay.isPresenting;
  90316. if (wasPresenting && !this._webVRpresenting)
  90317. this.exitVR();
  90318. }
  90319. else {
  90320. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  90321. }
  90322. this.updateButtonVisibility();
  90323. };
  90324. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  90325. this._webVRsupported = eventArgs.vrSupported;
  90326. this._webVRready = !!eventArgs.vrDisplay;
  90327. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  90328. this.updateButtonVisibility();
  90329. };
  90330. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  90331. if (this._canvas && !this._useCustomVRButton) {
  90332. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  90333. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  90334. }
  90335. };
  90336. VRExperienceHelper.prototype.displayVRButton = function () {
  90337. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  90338. document.body.appendChild(this._btnVR);
  90339. this._btnVRDisplayed = true;
  90340. }
  90341. };
  90342. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  90343. if (!this._btnVR || this._useCustomVRButton) {
  90344. return;
  90345. }
  90346. this._btnVR.className = "babylonVRicon";
  90347. if (this.isInVRMode) {
  90348. this._btnVR.className += " vrdisplaypresenting";
  90349. }
  90350. else {
  90351. if (this._webVRready)
  90352. this._btnVR.className += " vrdisplayready";
  90353. if (this._webVRsupported)
  90354. this._btnVR.className += " vrdisplaysupported";
  90355. if (this._webVRrequesting)
  90356. this._btnVR.className += " vrdisplayrequesting";
  90357. }
  90358. };
  90359. /**
  90360. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  90361. * Otherwise, will use the fullscreen API.
  90362. */
  90363. VRExperienceHelper.prototype.enterVR = function () {
  90364. if (this.onEnteringVRObservable) {
  90365. try {
  90366. this.onEnteringVRObservable.notifyObservers(this);
  90367. }
  90368. catch (err) {
  90369. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  90370. }
  90371. }
  90372. if (this._scene.activeCamera) {
  90373. this._position = this._scene.activeCamera.position.clone();
  90374. // make sure that we return to the last active camera
  90375. this._existingCamera = this._scene.activeCamera;
  90376. }
  90377. if (this._webVRrequesting)
  90378. return;
  90379. // If WebVR is supported and a headset is connected
  90380. if (this._webVRready) {
  90381. if (!this._webVRpresenting) {
  90382. this._webVRCamera.position = this._position;
  90383. this._scene.activeCamera = this._webVRCamera;
  90384. }
  90385. }
  90386. else if (this._vrDeviceOrientationCamera) {
  90387. this._vrDeviceOrientationCamera.position = this._position;
  90388. if (this._scene.activeCamera) {
  90389. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  90390. }
  90391. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  90392. this._scene.getEngine().switchFullscreen(true);
  90393. this.updateButtonVisibility();
  90394. }
  90395. if (this._scene.activeCamera && this._canvas) {
  90396. this._scene.activeCamera.attachControl(this._canvas);
  90397. }
  90398. if (this._interactionsEnabled) {
  90399. this._scene.registerBeforeRender(this.beforeRender);
  90400. }
  90401. };
  90402. /**
  90403. * Attempt to exit VR, or fullscreen.
  90404. */
  90405. VRExperienceHelper.prototype.exitVR = function () {
  90406. if (this.onExitingVRObservable) {
  90407. try {
  90408. this.onExitingVRObservable.notifyObservers(this);
  90409. }
  90410. catch (err) {
  90411. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  90412. }
  90413. }
  90414. if (this._webVRpresenting) {
  90415. this._scene.getEngine().disableVR();
  90416. }
  90417. if (this._scene.activeCamera) {
  90418. this._position = this._scene.activeCamera.position.clone();
  90419. }
  90420. if (this._deviceOrientationCamera) {
  90421. this._deviceOrientationCamera.position = this._position;
  90422. this._scene.activeCamera = this._deviceOrientationCamera;
  90423. if (this._canvas) {
  90424. this._scene.activeCamera.attachControl(this._canvas);
  90425. }
  90426. }
  90427. else if (this._existingCamera) {
  90428. this._existingCamera.position = this._position;
  90429. this._scene.activeCamera = this._existingCamera;
  90430. }
  90431. this.updateButtonVisibility();
  90432. if (this._interactionsEnabled) {
  90433. this._scene.unregisterBeforeRender(this.beforeRender);
  90434. }
  90435. // resize to update width and height when exiting vr exits fullscreen
  90436. this._scene.getEngine().resize();
  90437. };
  90438. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  90439. /**
  90440. * The position of the vr experience helper.
  90441. */
  90442. get: function () {
  90443. return this._position;
  90444. },
  90445. /**
  90446. * Sets the position of the vr experience helper.
  90447. */
  90448. set: function (value) {
  90449. this._position = value;
  90450. if (this._scene.activeCamera) {
  90451. this._scene.activeCamera.position = value;
  90452. }
  90453. },
  90454. enumerable: true,
  90455. configurable: true
  90456. });
  90457. /**
  90458. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  90459. */
  90460. VRExperienceHelper.prototype.enableInteractions = function () {
  90461. var _this = this;
  90462. if (!this._interactionsEnabled) {
  90463. this._interactionsRequested = true;
  90464. if (this.leftController) {
  90465. this._enableInteractionOnController(this.leftController);
  90466. }
  90467. if (this.rightController) {
  90468. this._enableInteractionOnController(this.rightController);
  90469. }
  90470. this.raySelectionPredicate = function (mesh) {
  90471. return mesh.isVisible;
  90472. };
  90473. this.meshSelectionPredicate = function (mesh) {
  90474. return true;
  90475. };
  90476. this._raySelectionPredicate = function (mesh) {
  90477. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  90478. && mesh.name.indexOf("teleportationTarget") === -1
  90479. && mesh.name.indexOf("torusTeleportation") === -1
  90480. && mesh.name.indexOf("laserPointer") === -1)) {
  90481. return _this.raySelectionPredicate(mesh);
  90482. }
  90483. return false;
  90484. };
  90485. this._interactionsEnabled = true;
  90486. }
  90487. };
  90488. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  90489. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  90490. if (this._floorMeshesCollection[i].id === mesh.id) {
  90491. return true;
  90492. }
  90493. }
  90494. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  90495. return true;
  90496. }
  90497. return false;
  90498. };
  90499. /**
  90500. * Adds a floor mesh to be used for teleportation.
  90501. * @param floorMesh the mesh to be used for teleportation.
  90502. */
  90503. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  90504. if (!this._floorMeshesCollection) {
  90505. return;
  90506. }
  90507. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  90508. return;
  90509. }
  90510. this._floorMeshesCollection.push(floorMesh);
  90511. };
  90512. /**
  90513. * Removes a floor mesh from being used for teleportation.
  90514. * @param floorMesh the mesh to be removed.
  90515. */
  90516. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  90517. if (!this._floorMeshesCollection) {
  90518. return;
  90519. }
  90520. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  90521. if (meshIndex !== -1) {
  90522. this._floorMeshesCollection.splice(meshIndex, 1);
  90523. }
  90524. };
  90525. /**
  90526. * Enables interactions and teleportation using the VR controllers and gaze.
  90527. * @param vrTeleportationOptions options to modify teleportation behavior.
  90528. */
  90529. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  90530. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  90531. if (!this._teleportationInitialized) {
  90532. this._teleportationRequested = true;
  90533. this.enableInteractions();
  90534. if (vrTeleportationOptions.floorMeshName) {
  90535. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  90536. }
  90537. if (vrTeleportationOptions.floorMeshes) {
  90538. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  90539. }
  90540. if (this.leftController != null) {
  90541. this._enableTeleportationOnController(this.leftController);
  90542. }
  90543. if (this.rightController != null) {
  90544. this._enableTeleportationOnController(this.rightController);
  90545. }
  90546. // Creates an image processing post process for the vignette not relying
  90547. // on the main scene configuration for image processing to reduce setup and spaces
  90548. // (gamma/linear) conflicts.
  90549. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  90550. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  90551. imageProcessingConfiguration.vignetteEnabled = true;
  90552. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  90553. this._webVRCamera.detachPostProcess(this._postProcessMove);
  90554. this._teleportationInitialized = true;
  90555. if (this._isDefaultTeleportationTarget) {
  90556. this._createTeleportationCircles();
  90557. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  90558. }
  90559. }
  90560. };
  90561. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  90562. var _this = this;
  90563. var controllerMesh = controller.webVRController.mesh;
  90564. if (controllerMesh) {
  90565. controller._interactionsEnabled = true;
  90566. controller._activatePointer();
  90567. if (this.webVROptions.laserToggle) {
  90568. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  90569. // Enabling / disabling laserPointer
  90570. if (_this._displayLaserPointer && stateObject.value === 1) {
  90571. if (controller._activePointer) {
  90572. controller._deactivatePointer();
  90573. }
  90574. else {
  90575. controller._activatePointer();
  90576. }
  90577. if (_this.displayGaze) {
  90578. controller._gazeTracker.isVisible = controller._activePointer;
  90579. }
  90580. }
  90581. });
  90582. }
  90583. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  90584. if (!controller._pointerDownOnMeshAsked) {
  90585. if (stateObject.value > _this._padSensibilityUp) {
  90586. controller._selectionPointerDown();
  90587. }
  90588. }
  90589. else if (stateObject.value < _this._padSensibilityDown) {
  90590. controller._selectionPointerUp();
  90591. }
  90592. });
  90593. }
  90594. };
  90595. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  90596. // Dont teleport if another gaze already requested teleportation
  90597. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  90598. return;
  90599. }
  90600. if (!gazer._teleportationRequestInitiated) {
  90601. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  90602. gazer._activatePointer();
  90603. gazer._teleportationRequestInitiated = true;
  90604. }
  90605. }
  90606. else {
  90607. // Listening to the proper controller values changes to confirm teleportation
  90608. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  90609. if (this._teleportActive) {
  90610. this._teleportCamera(this._haloCenter);
  90611. }
  90612. gazer._teleportationRequestInitiated = false;
  90613. }
  90614. }
  90615. };
  90616. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  90617. // Only rotate when user is not currently selecting a teleportation location
  90618. if (gazer._teleportationRequestInitiated) {
  90619. return;
  90620. }
  90621. if (!gazer._rotationLeftAsked) {
  90622. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  90623. gazer._rotationLeftAsked = true;
  90624. if (this._rotationAllowed) {
  90625. this._rotateCamera(false);
  90626. }
  90627. }
  90628. }
  90629. else {
  90630. if (stateObject.x > -this._padSensibilityDown) {
  90631. gazer._rotationLeftAsked = false;
  90632. }
  90633. }
  90634. if (!gazer._rotationRightAsked) {
  90635. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  90636. gazer._rotationRightAsked = true;
  90637. if (this._rotationAllowed) {
  90638. this._rotateCamera(true);
  90639. }
  90640. }
  90641. }
  90642. else {
  90643. if (stateObject.x < this._padSensibilityDown) {
  90644. gazer._rotationRightAsked = false;
  90645. }
  90646. }
  90647. };
  90648. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  90649. // Only teleport backwards when user is not currently selecting a teleportation location
  90650. if (gazer._teleportationRequestInitiated) {
  90651. return;
  90652. }
  90653. // Teleport backwards
  90654. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  90655. if (!gazer._teleportationBackRequestInitiated) {
  90656. if (!this.currentVRCamera) {
  90657. return;
  90658. }
  90659. // Get rotation and position of the current camera
  90660. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  90661. var position = this.currentVRCamera.position;
  90662. // If the camera has device position, use that instead
  90663. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  90664. rotation = this.currentVRCamera.deviceRotationQuaternion;
  90665. position = this.currentVRCamera.devicePosition;
  90666. }
  90667. // Get matrix with only the y rotation of the device rotation
  90668. rotation.toEulerAnglesToRef(this._workingVector);
  90669. this._workingVector.z = 0;
  90670. this._workingVector.x = 0;
  90671. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  90672. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  90673. // Rotate backwards ray by device rotation to cast at the ground behind the user
  90674. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  90675. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  90676. var ray = new BABYLON.Ray(position, this._workingVector);
  90677. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90678. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  90679. this._teleportCamera(hit.pickedPoint);
  90680. }
  90681. gazer._teleportationBackRequestInitiated = true;
  90682. }
  90683. }
  90684. else {
  90685. gazer._teleportationBackRequestInitiated = false;
  90686. }
  90687. };
  90688. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  90689. var _this = this;
  90690. var controllerMesh = controller.webVRController.mesh;
  90691. if (controllerMesh) {
  90692. if (!controller._interactionsEnabled) {
  90693. this._enableInteractionOnController(controller);
  90694. }
  90695. controller._interactionsEnabled = true;
  90696. controller._teleportationEnabled = true;
  90697. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90698. controller._dpadPressed = false;
  90699. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  90700. controller._dpadPressed = stateObject.pressed;
  90701. if (!controller._dpadPressed) {
  90702. controller._rotationLeftAsked = false;
  90703. controller._rotationRightAsked = false;
  90704. controller._teleportationBackRequestInitiated = false;
  90705. }
  90706. });
  90707. }
  90708. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  90709. if (_this.teleportationEnabled) {
  90710. _this._checkTeleportBackwards(stateObject, controller);
  90711. _this._checkTeleportWithRay(stateObject, controller);
  90712. }
  90713. _this._checkRotate(stateObject, controller);
  90714. });
  90715. }
  90716. };
  90717. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  90718. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  90719. this._teleportationTarget.isPickable = false;
  90720. var length = 512;
  90721. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  90722. dynamicTexture.hasAlpha = true;
  90723. var context = dynamicTexture.getContext();
  90724. var centerX = length / 2;
  90725. var centerY = length / 2;
  90726. var radius = 200;
  90727. context.beginPath();
  90728. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  90729. context.fillStyle = this._teleportationFillColor;
  90730. context.fill();
  90731. context.lineWidth = 10;
  90732. context.strokeStyle = this._teleportationBorderColor;
  90733. context.stroke();
  90734. context.closePath();
  90735. dynamicTexture.update();
  90736. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  90737. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  90738. this._teleportationTarget.material = teleportationCircleMaterial;
  90739. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  90740. torus.isPickable = false;
  90741. torus.parent = this._teleportationTarget;
  90742. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90743. var keys = [];
  90744. keys.push({
  90745. frame: 0,
  90746. value: 0
  90747. });
  90748. keys.push({
  90749. frame: 30,
  90750. value: 0.4
  90751. });
  90752. keys.push({
  90753. frame: 60,
  90754. value: 0
  90755. });
  90756. animationInnerCircle.setKeys(keys);
  90757. var easingFunction = new BABYLON.SineEase();
  90758. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90759. animationInnerCircle.setEasingFunction(easingFunction);
  90760. torus.animations = [];
  90761. torus.animations.push(animationInnerCircle);
  90762. this._scene.beginAnimation(torus, 0, 60, true);
  90763. this._hideTeleportationTarget();
  90764. };
  90765. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  90766. this._teleportActive = true;
  90767. if (this._teleportationInitialized) {
  90768. this._teleportationTarget.isVisible = true;
  90769. if (this._isDefaultTeleportationTarget) {
  90770. this._teleportationTarget.getChildren()[0].isVisible = true;
  90771. }
  90772. }
  90773. };
  90774. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  90775. this._teleportActive = false;
  90776. if (this._teleportationInitialized) {
  90777. this._teleportationTarget.isVisible = false;
  90778. if (this._isDefaultTeleportationTarget) {
  90779. this._teleportationTarget.getChildren()[0].isVisible = false;
  90780. }
  90781. }
  90782. };
  90783. VRExperienceHelper.prototype._rotateCamera = function (right) {
  90784. var _this = this;
  90785. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90786. return;
  90787. }
  90788. if (right) {
  90789. this._rotationAngle++;
  90790. }
  90791. else {
  90792. this._rotationAngle--;
  90793. }
  90794. this.currentVRCamera.animations = [];
  90795. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  90796. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90797. var animationRotationKeys = [];
  90798. animationRotationKeys.push({
  90799. frame: 0,
  90800. value: this.currentVRCamera.rotationQuaternion
  90801. });
  90802. animationRotationKeys.push({
  90803. frame: 6,
  90804. value: target
  90805. });
  90806. animationRotation.setKeys(animationRotationKeys);
  90807. animationRotation.setEasingFunction(this._circleEase);
  90808. this.currentVRCamera.animations.push(animationRotation);
  90809. this._postProcessMove.animations = [];
  90810. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90811. var vignetteWeightKeys = [];
  90812. vignetteWeightKeys.push({
  90813. frame: 0,
  90814. value: 0
  90815. });
  90816. vignetteWeightKeys.push({
  90817. frame: 3,
  90818. value: 4
  90819. });
  90820. vignetteWeightKeys.push({
  90821. frame: 6,
  90822. value: 0
  90823. });
  90824. animationPP.setKeys(vignetteWeightKeys);
  90825. animationPP.setEasingFunction(this._circleEase);
  90826. this._postProcessMove.animations.push(animationPP);
  90827. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90828. var vignetteStretchKeys = [];
  90829. vignetteStretchKeys.push({
  90830. frame: 0,
  90831. value: 0
  90832. });
  90833. vignetteStretchKeys.push({
  90834. frame: 3,
  90835. value: 10
  90836. });
  90837. vignetteStretchKeys.push({
  90838. frame: 6,
  90839. value: 0
  90840. });
  90841. animationPP2.setKeys(vignetteStretchKeys);
  90842. animationPP2.setEasingFunction(this._circleEase);
  90843. this._postProcessMove.animations.push(animationPP2);
  90844. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90845. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90846. this._postProcessMove.samples = 4;
  90847. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90848. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  90849. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90850. });
  90851. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  90852. };
  90853. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  90854. if (hit.pickedPoint) {
  90855. if (gazer._teleportationRequestInitiated) {
  90856. this._displayTeleportationTarget();
  90857. this._haloCenter.copyFrom(hit.pickedPoint);
  90858. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  90859. }
  90860. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  90861. if (pickNormal) {
  90862. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  90863. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  90864. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  90865. }
  90866. this._teleportationTarget.position.y += 0.1;
  90867. }
  90868. };
  90869. VRExperienceHelper.prototype._teleportCamera = function (location) {
  90870. var _this = this;
  90871. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90872. return;
  90873. }
  90874. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  90875. // offset of the headset from the anchor.
  90876. if (this.webVRCamera.leftCamera) {
  90877. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  90878. this._workingVector.subtractInPlace(this.webVRCamera.position);
  90879. location.subtractToRef(this._workingVector, this._workingVector);
  90880. }
  90881. else {
  90882. this._workingVector.copyFrom(location);
  90883. }
  90884. // Add height to account for user's height offset
  90885. if (this.isInVRMode) {
  90886. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  90887. }
  90888. else {
  90889. this._workingVector.y += this._defaultHeight;
  90890. }
  90891. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  90892. // Create animation from the camera's position to the new location
  90893. this.currentVRCamera.animations = [];
  90894. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90895. var animationCameraTeleportationKeys = [{
  90896. frame: 0,
  90897. value: this.currentVRCamera.position
  90898. },
  90899. {
  90900. frame: 11,
  90901. value: this._workingVector
  90902. }
  90903. ];
  90904. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  90905. animationCameraTeleportation.setEasingFunction(this._circleEase);
  90906. this.currentVRCamera.animations.push(animationCameraTeleportation);
  90907. this._postProcessMove.animations = [];
  90908. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90909. var vignetteWeightKeys = [];
  90910. vignetteWeightKeys.push({
  90911. frame: 0,
  90912. value: 0
  90913. });
  90914. vignetteWeightKeys.push({
  90915. frame: 5,
  90916. value: 8
  90917. });
  90918. vignetteWeightKeys.push({
  90919. frame: 11,
  90920. value: 0
  90921. });
  90922. animationPP.setKeys(vignetteWeightKeys);
  90923. this._postProcessMove.animations.push(animationPP);
  90924. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90925. var vignetteStretchKeys = [];
  90926. vignetteStretchKeys.push({
  90927. frame: 0,
  90928. value: 0
  90929. });
  90930. vignetteStretchKeys.push({
  90931. frame: 5,
  90932. value: 10
  90933. });
  90934. vignetteStretchKeys.push({
  90935. frame: 11,
  90936. value: 0
  90937. });
  90938. animationPP2.setKeys(vignetteStretchKeys);
  90939. this._postProcessMove.animations.push(animationPP2);
  90940. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90941. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90942. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90943. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  90944. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90945. });
  90946. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  90947. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  90948. });
  90949. this._hideTeleportationTarget();
  90950. };
  90951. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  90952. if (normal) {
  90953. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  90954. if (angle < Math.PI / 2) {
  90955. normal.scaleInPlace(-1);
  90956. }
  90957. }
  90958. return normal;
  90959. };
  90960. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  90961. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90962. return;
  90963. }
  90964. var ray = gazer._getForwardRay(this._rayLength);
  90965. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90966. if (hit) {
  90967. // Populate the contrllers mesh that can be used for drag/drop
  90968. if (gazer._laserPointer) {
  90969. hit.originMesh = gazer._laserPointer.parent;
  90970. }
  90971. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  90972. }
  90973. gazer._currentHit = hit;
  90974. // Moving the gazeTracker on the mesh face targetted
  90975. if (hit && hit.pickedPoint) {
  90976. if (this._displayGaze) {
  90977. var multiplier = 1;
  90978. gazer._gazeTracker.isVisible = true;
  90979. if (gazer._isActionableMesh) {
  90980. multiplier = 3;
  90981. }
  90982. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  90983. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  90984. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  90985. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  90986. // To avoid z-fighting
  90987. var deltaFighting = 0.002;
  90988. if (pickNormal) {
  90989. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  90990. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  90991. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  90992. }
  90993. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  90994. if (gazer._gazeTracker.position.x < 0) {
  90995. gazer._gazeTracker.position.x += deltaFighting;
  90996. }
  90997. else {
  90998. gazer._gazeTracker.position.x -= deltaFighting;
  90999. }
  91000. if (gazer._gazeTracker.position.y < 0) {
  91001. gazer._gazeTracker.position.y += deltaFighting;
  91002. }
  91003. else {
  91004. gazer._gazeTracker.position.y -= deltaFighting;
  91005. }
  91006. if (gazer._gazeTracker.position.z < 0) {
  91007. gazer._gazeTracker.position.z += deltaFighting;
  91008. }
  91009. else {
  91010. gazer._gazeTracker.position.z -= deltaFighting;
  91011. }
  91012. }
  91013. // Changing the size of the laser pointer based on the distance from the targetted point
  91014. gazer._updatePointerDistance(hit.distance);
  91015. }
  91016. else {
  91017. gazer._updatePointerDistance();
  91018. gazer._gazeTracker.isVisible = false;
  91019. }
  91020. if (hit && hit.pickedMesh) {
  91021. // The object selected is the floor, we're in a teleportation scenario
  91022. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  91023. // Moving the teleportation area to this targetted point
  91024. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  91025. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  91026. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91027. }
  91028. gazer._currentMeshSelected = null;
  91029. if (gazer._teleportationRequestInitiated) {
  91030. this._moveTeleportationSelectorTo(hit, gazer, ray);
  91031. }
  91032. return;
  91033. }
  91034. // If not, we're in a selection scenario
  91035. //this._teleportationAllowed = false;
  91036. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  91037. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  91038. this.onNewMeshPicked.notifyObservers(hit);
  91039. gazer._currentMeshSelected = hit.pickedMesh;
  91040. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  91041. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  91042. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  91043. gazer._isActionableMesh = true;
  91044. }
  91045. else {
  91046. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91047. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91048. gazer._isActionableMesh = false;
  91049. }
  91050. try {
  91051. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  91052. }
  91053. catch (err) {
  91054. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  91055. }
  91056. }
  91057. else {
  91058. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91059. gazer._currentMeshSelected = null;
  91060. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91061. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91062. }
  91063. }
  91064. }
  91065. else {
  91066. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  91067. gazer._currentMeshSelected = null;
  91068. //this._teleportationAllowed = false;
  91069. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91070. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  91071. }
  91072. };
  91073. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  91074. if (mesh) {
  91075. this.onSelectedMeshUnselected.notifyObservers(mesh);
  91076. }
  91077. };
  91078. /**
  91079. * Sets the color of the laser ray from the vr controllers.
  91080. * @param color new color for the ray.
  91081. */
  91082. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  91083. if (this.leftController) {
  91084. this.leftController._setLaserPointerColor(color);
  91085. }
  91086. if (this.rightController) {
  91087. this.rightController._setLaserPointerColor(color);
  91088. }
  91089. };
  91090. /**
  91091. * Sets the color of the ray from the vr headsets gaze.
  91092. * @param color new color for the ray.
  91093. */
  91094. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  91095. if (!this._cameraGazer._gazeTracker.material) {
  91096. return;
  91097. }
  91098. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  91099. if (this.leftController) {
  91100. this.leftController._gazeTracker.material.emissiveColor = color;
  91101. }
  91102. if (this.rightController) {
  91103. this.rightController._gazeTracker.material.emissiveColor = color;
  91104. }
  91105. };
  91106. /**
  91107. * Exits VR and disposes of the vr experience helper
  91108. */
  91109. VRExperienceHelper.prototype.dispose = function () {
  91110. if (this.isInVRMode) {
  91111. this.exitVR();
  91112. }
  91113. if (this._postProcessMove) {
  91114. this._postProcessMove.dispose();
  91115. }
  91116. if (this._webVRCamera) {
  91117. this._webVRCamera.dispose();
  91118. }
  91119. if (this._vrDeviceOrientationCamera) {
  91120. this._vrDeviceOrientationCamera.dispose();
  91121. }
  91122. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  91123. document.body.removeChild(this._btnVR);
  91124. }
  91125. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  91126. this._deviceOrientationCamera.dispose();
  91127. }
  91128. if (this._cameraGazer) {
  91129. this._cameraGazer.dispose();
  91130. }
  91131. if (this.leftController) {
  91132. this.leftController.dispose();
  91133. }
  91134. if (this.rightController) {
  91135. this.rightController.dispose();
  91136. }
  91137. if (this._teleportationTarget) {
  91138. this._teleportationTarget.dispose();
  91139. }
  91140. this._floorMeshesCollection = [];
  91141. document.removeEventListener("keydown", this._onKeyDown);
  91142. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91143. window.removeEventListener("resize", this._onResize);
  91144. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  91145. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  91146. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  91147. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  91148. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  91149. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  91150. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  91151. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91152. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  91153. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  91154. this._scene.unregisterBeforeRender(this.beforeRender);
  91155. };
  91156. /**
  91157. * Gets the name of the VRExperienceHelper class
  91158. * @returns "VRExperienceHelper"
  91159. */
  91160. VRExperienceHelper.prototype.getClassName = function () {
  91161. return "VRExperienceHelper";
  91162. };
  91163. return VRExperienceHelper;
  91164. }());
  91165. BABYLON.VRExperienceHelper = VRExperienceHelper;
  91166. })(BABYLON || (BABYLON = {}));
  91167. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  91168. // Mainly based on these 2 articles :
  91169. // 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
  91170. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  91171. var BABYLON;
  91172. (function (BABYLON) {
  91173. /**
  91174. * Defines the potential axis of a Joystick
  91175. */
  91176. var JoystickAxis;
  91177. (function (JoystickAxis) {
  91178. /** X axis */
  91179. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  91180. /** Y axis */
  91181. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  91182. /** Z axis */
  91183. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  91184. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  91185. /**
  91186. * Class used to define virtual joystick (used in touch mode)
  91187. */
  91188. var VirtualJoystick = /** @class */ (function () {
  91189. /**
  91190. * Creates a new virtual joystick
  91191. * @param leftJoystick defines that the joystick is for left hand (false by default)
  91192. */
  91193. function VirtualJoystick(leftJoystick) {
  91194. var _this = this;
  91195. if (leftJoystick) {
  91196. this._leftJoystick = true;
  91197. }
  91198. else {
  91199. this._leftJoystick = false;
  91200. }
  91201. VirtualJoystick._globalJoystickIndex++;
  91202. // By default left & right arrow keys are moving the X
  91203. // and up & down keys are moving the Y
  91204. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91205. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91206. this.reverseLeftRight = false;
  91207. this.reverseUpDown = false;
  91208. // collections of pointers
  91209. this._touches = new BABYLON.StringDictionary();
  91210. this.deltaPosition = BABYLON.Vector3.Zero();
  91211. this._joystickSensibility = 25;
  91212. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91213. this._onResize = function (evt) {
  91214. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91215. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91216. if (VirtualJoystick.vjCanvas) {
  91217. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  91218. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  91219. }
  91220. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  91221. };
  91222. // injecting a canvas element on top of the canvas 3D game
  91223. if (!VirtualJoystick.vjCanvas) {
  91224. window.addEventListener("resize", this._onResize, false);
  91225. VirtualJoystick.vjCanvas = document.createElement("canvas");
  91226. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  91227. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  91228. VirtualJoystick.vjCanvas.width = window.innerWidth;
  91229. VirtualJoystick.vjCanvas.height = window.innerHeight;
  91230. VirtualJoystick.vjCanvas.style.width = "100%";
  91231. VirtualJoystick.vjCanvas.style.height = "100%";
  91232. VirtualJoystick.vjCanvas.style.position = "absolute";
  91233. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  91234. VirtualJoystick.vjCanvas.style.top = "0px";
  91235. VirtualJoystick.vjCanvas.style.left = "0px";
  91236. VirtualJoystick.vjCanvas.style.zIndex = "5";
  91237. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  91238. // Support for jQuery PEP polyfill
  91239. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  91240. var context = VirtualJoystick.vjCanvas.getContext('2d');
  91241. if (!context) {
  91242. throw new Error("Unable to create canvas for virtual joystick");
  91243. }
  91244. VirtualJoystick.vjCanvasContext = context;
  91245. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  91246. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91247. document.body.appendChild(VirtualJoystick.vjCanvas);
  91248. }
  91249. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  91250. this.pressed = false;
  91251. // default joystick color
  91252. this._joystickColor = "cyan";
  91253. this._joystickPointerID = -1;
  91254. // current joystick position
  91255. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  91256. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  91257. // origin joystick position
  91258. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  91259. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  91260. this._onPointerDownHandlerRef = function (evt) {
  91261. _this._onPointerDown(evt);
  91262. };
  91263. this._onPointerMoveHandlerRef = function (evt) {
  91264. _this._onPointerMove(evt);
  91265. };
  91266. this._onPointerUpHandlerRef = function (evt) {
  91267. _this._onPointerUp(evt);
  91268. };
  91269. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  91270. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  91271. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  91272. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  91273. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  91274. evt.preventDefault(); // Disables system menu
  91275. }, false);
  91276. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91277. }
  91278. /**
  91279. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  91280. * @param newJoystickSensibility defines the new sensibility
  91281. */
  91282. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  91283. this._joystickSensibility = newJoystickSensibility;
  91284. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  91285. };
  91286. VirtualJoystick.prototype._onPointerDown = function (e) {
  91287. var positionOnScreenCondition;
  91288. e.preventDefault();
  91289. if (this._leftJoystick === true) {
  91290. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  91291. }
  91292. else {
  91293. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  91294. }
  91295. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  91296. // First contact will be dedicated to the virtual joystick
  91297. this._joystickPointerID = e.pointerId;
  91298. this._joystickPointerStartPos.x = e.clientX;
  91299. this._joystickPointerStartPos.y = e.clientY;
  91300. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  91301. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  91302. this._deltaJoystickVector.x = 0;
  91303. this._deltaJoystickVector.y = 0;
  91304. this.pressed = true;
  91305. this._touches.add(e.pointerId.toString(), e);
  91306. }
  91307. else {
  91308. // You can only trigger the action buttons with a joystick declared
  91309. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  91310. this._action();
  91311. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  91312. }
  91313. }
  91314. };
  91315. VirtualJoystick.prototype._onPointerMove = function (e) {
  91316. // If the current pointer is the one associated to the joystick (first touch contact)
  91317. if (this._joystickPointerID == e.pointerId) {
  91318. this._joystickPointerPos.x = e.clientX;
  91319. this._joystickPointerPos.y = e.clientY;
  91320. this._deltaJoystickVector = this._joystickPointerPos.clone();
  91321. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  91322. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  91323. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  91324. switch (this._axisTargetedByLeftAndRight) {
  91325. case JoystickAxis.X:
  91326. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  91327. break;
  91328. case JoystickAxis.Y:
  91329. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  91330. break;
  91331. case JoystickAxis.Z:
  91332. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  91333. break;
  91334. }
  91335. var directionUpDown = this.reverseUpDown ? 1 : -1;
  91336. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  91337. switch (this._axisTargetedByUpAndDown) {
  91338. case JoystickAxis.X:
  91339. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  91340. break;
  91341. case JoystickAxis.Y:
  91342. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  91343. break;
  91344. case JoystickAxis.Z:
  91345. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  91346. break;
  91347. }
  91348. }
  91349. else {
  91350. var data = this._touches.get(e.pointerId.toString());
  91351. if (data) {
  91352. data.x = e.clientX;
  91353. data.y = e.clientY;
  91354. }
  91355. }
  91356. };
  91357. VirtualJoystick.prototype._onPointerUp = function (e) {
  91358. if (this._joystickPointerID == e.pointerId) {
  91359. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  91360. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  91361. this._joystickPointerID = -1;
  91362. this.pressed = false;
  91363. }
  91364. else {
  91365. var touch = this._touches.get(e.pointerId.toString());
  91366. if (touch) {
  91367. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91368. }
  91369. }
  91370. this._deltaJoystickVector.x = 0;
  91371. this._deltaJoystickVector.y = 0;
  91372. this._touches.remove(e.pointerId.toString());
  91373. };
  91374. /**
  91375. * Change the color of the virtual joystick
  91376. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  91377. */
  91378. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  91379. this._joystickColor = newColor;
  91380. };
  91381. /**
  91382. * Defines a callback to call when the joystick is touched
  91383. * @param action defines the callback
  91384. */
  91385. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  91386. this._action = action;
  91387. };
  91388. /**
  91389. * Defines which axis you'd like to control for left & right
  91390. * @param axis defines the axis to use
  91391. */
  91392. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  91393. switch (axis) {
  91394. case JoystickAxis.X:
  91395. case JoystickAxis.Y:
  91396. case JoystickAxis.Z:
  91397. this._axisTargetedByLeftAndRight = axis;
  91398. break;
  91399. default:
  91400. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  91401. break;
  91402. }
  91403. };
  91404. /**
  91405. * Defines which axis you'd like to control for up & down
  91406. * @param axis defines the axis to use
  91407. */
  91408. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  91409. switch (axis) {
  91410. case JoystickAxis.X:
  91411. case JoystickAxis.Y:
  91412. case JoystickAxis.Z:
  91413. this._axisTargetedByUpAndDown = axis;
  91414. break;
  91415. default:
  91416. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  91417. break;
  91418. }
  91419. };
  91420. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  91421. var _this = this;
  91422. if (this.pressed) {
  91423. this._touches.forEach(function (key, touch) {
  91424. if (touch.pointerId === _this._joystickPointerID) {
  91425. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  91426. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  91427. VirtualJoystick.vjCanvasContext.beginPath();
  91428. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91429. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91430. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  91431. VirtualJoystick.vjCanvasContext.stroke();
  91432. VirtualJoystick.vjCanvasContext.closePath();
  91433. VirtualJoystick.vjCanvasContext.beginPath();
  91434. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91435. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  91436. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  91437. VirtualJoystick.vjCanvasContext.stroke();
  91438. VirtualJoystick.vjCanvasContext.closePath();
  91439. VirtualJoystick.vjCanvasContext.beginPath();
  91440. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  91441. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  91442. VirtualJoystick.vjCanvasContext.stroke();
  91443. VirtualJoystick.vjCanvasContext.closePath();
  91444. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  91445. }
  91446. else {
  91447. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  91448. VirtualJoystick.vjCanvasContext.beginPath();
  91449. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  91450. VirtualJoystick.vjCanvasContext.beginPath();
  91451. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  91452. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  91453. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  91454. VirtualJoystick.vjCanvasContext.stroke();
  91455. VirtualJoystick.vjCanvasContext.closePath();
  91456. touch.prevX = touch.x;
  91457. touch.prevY = touch.y;
  91458. }
  91459. ;
  91460. });
  91461. }
  91462. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  91463. };
  91464. /**
  91465. * Release internal HTML canvas
  91466. */
  91467. VirtualJoystick.prototype.releaseCanvas = function () {
  91468. if (VirtualJoystick.vjCanvas) {
  91469. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  91470. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  91471. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  91472. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  91473. window.removeEventListener("resize", this._onResize);
  91474. document.body.removeChild(VirtualJoystick.vjCanvas);
  91475. VirtualJoystick.vjCanvas = null;
  91476. }
  91477. };
  91478. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  91479. VirtualJoystick._globalJoystickIndex = 0;
  91480. return VirtualJoystick;
  91481. }());
  91482. BABYLON.VirtualJoystick = VirtualJoystick;
  91483. })(BABYLON || (BABYLON = {}));
  91484. //# sourceMappingURL=babylon.virtualJoystick.js.map
  91485. var BABYLON;
  91486. (function (BABYLON) {
  91487. // We're mainly based on the logic defined into the FreeCamera code
  91488. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  91489. __extends(VirtualJoysticksCamera, _super);
  91490. function VirtualJoysticksCamera(name, position, scene) {
  91491. var _this = _super.call(this, name, position, scene) || this;
  91492. _this.inputs.addVirtualJoystick();
  91493. return _this;
  91494. }
  91495. VirtualJoysticksCamera.prototype.getClassName = function () {
  91496. return "VirtualJoysticksCamera";
  91497. };
  91498. return VirtualJoysticksCamera;
  91499. }(BABYLON.FreeCamera));
  91500. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  91501. })(BABYLON || (BABYLON = {}));
  91502. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  91503. var BABYLON;
  91504. (function (BABYLON) {
  91505. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  91506. function FreeCameraVirtualJoystickInput() {
  91507. }
  91508. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  91509. return this._leftjoystick;
  91510. };
  91511. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  91512. return this._rightjoystick;
  91513. };
  91514. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  91515. if (this._leftjoystick) {
  91516. var camera = this.camera;
  91517. var speed = camera._computeLocalCameraSpeed() * 50;
  91518. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  91519. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  91520. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  91521. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  91522. if (!this._leftjoystick.pressed) {
  91523. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  91524. }
  91525. if (!this._rightjoystick.pressed) {
  91526. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  91527. }
  91528. }
  91529. };
  91530. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  91531. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  91532. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  91533. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  91534. this._leftjoystick.setJoystickSensibility(0.15);
  91535. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  91536. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  91537. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  91538. this._rightjoystick.reverseUpDown = true;
  91539. this._rightjoystick.setJoystickSensibility(0.05);
  91540. this._rightjoystick.setJoystickColor("yellow");
  91541. };
  91542. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  91543. this._leftjoystick.releaseCanvas();
  91544. this._rightjoystick.releaseCanvas();
  91545. };
  91546. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  91547. return "FreeCameraVirtualJoystickInput";
  91548. };
  91549. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  91550. return "virtualJoystick";
  91551. };
  91552. return FreeCameraVirtualJoystickInput;
  91553. }());
  91554. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  91555. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  91556. })(BABYLON || (BABYLON = {}));
  91557. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  91558. var BABYLON;
  91559. (function (BABYLON) {
  91560. var SimplificationSettings = /** @class */ (function () {
  91561. function SimplificationSettings(quality, distance, optimizeMesh) {
  91562. this.quality = quality;
  91563. this.distance = distance;
  91564. this.optimizeMesh = optimizeMesh;
  91565. }
  91566. return SimplificationSettings;
  91567. }());
  91568. BABYLON.SimplificationSettings = SimplificationSettings;
  91569. var SimplificationQueue = /** @class */ (function () {
  91570. function SimplificationQueue() {
  91571. this.running = false;
  91572. this._simplificationArray = [];
  91573. }
  91574. SimplificationQueue.prototype.addTask = function (task) {
  91575. this._simplificationArray.push(task);
  91576. };
  91577. SimplificationQueue.prototype.executeNext = function () {
  91578. var task = this._simplificationArray.pop();
  91579. if (task) {
  91580. this.running = true;
  91581. this.runSimplification(task);
  91582. }
  91583. else {
  91584. this.running = false;
  91585. }
  91586. };
  91587. SimplificationQueue.prototype.runSimplification = function (task) {
  91588. var _this = this;
  91589. if (task.parallelProcessing) {
  91590. //parallel simplifier
  91591. task.settings.forEach(function (setting) {
  91592. var simplifier = _this.getSimplifier(task);
  91593. simplifier.simplify(setting, function (newMesh) {
  91594. task.mesh.addLODLevel(setting.distance, newMesh);
  91595. newMesh.isVisible = true;
  91596. //check if it is the last
  91597. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  91598. //all done, run the success callback.
  91599. task.successCallback();
  91600. }
  91601. _this.executeNext();
  91602. });
  91603. });
  91604. }
  91605. else {
  91606. //single simplifier.
  91607. var simplifier = this.getSimplifier(task);
  91608. var runDecimation = function (setting, callback) {
  91609. simplifier.simplify(setting, function (newMesh) {
  91610. task.mesh.addLODLevel(setting.distance, newMesh);
  91611. newMesh.isVisible = true;
  91612. //run the next quality level
  91613. callback();
  91614. });
  91615. };
  91616. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  91617. runDecimation(task.settings[loop.index], function () {
  91618. loop.executeNext();
  91619. });
  91620. }, function () {
  91621. //execution ended, run the success callback.
  91622. if (task.successCallback) {
  91623. task.successCallback();
  91624. }
  91625. _this.executeNext();
  91626. });
  91627. }
  91628. };
  91629. SimplificationQueue.prototype.getSimplifier = function (task) {
  91630. switch (task.simplificationType) {
  91631. case SimplificationType.QUADRATIC:
  91632. default:
  91633. return new QuadraticErrorSimplification(task.mesh);
  91634. }
  91635. };
  91636. return SimplificationQueue;
  91637. }());
  91638. BABYLON.SimplificationQueue = SimplificationQueue;
  91639. /**
  91640. * The implemented types of simplification
  91641. * At the moment only Quadratic Error Decimation is implemented
  91642. */
  91643. var SimplificationType;
  91644. (function (SimplificationType) {
  91645. /** Quadratic error decimation */
  91646. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  91647. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  91648. var DecimationTriangle = /** @class */ (function () {
  91649. function DecimationTriangle(vertices) {
  91650. this.vertices = vertices;
  91651. this.error = new Array(4);
  91652. this.deleted = false;
  91653. this.isDirty = false;
  91654. this.deletePending = false;
  91655. this.borderFactor = 0;
  91656. }
  91657. return DecimationTriangle;
  91658. }());
  91659. BABYLON.DecimationTriangle = DecimationTriangle;
  91660. var DecimationVertex = /** @class */ (function () {
  91661. function DecimationVertex(position, id) {
  91662. this.position = position;
  91663. this.id = id;
  91664. this.isBorder = true;
  91665. this.q = new QuadraticMatrix();
  91666. this.triangleCount = 0;
  91667. this.triangleStart = 0;
  91668. this.originalOffsets = [];
  91669. }
  91670. DecimationVertex.prototype.updatePosition = function (newPosition) {
  91671. this.position.copyFrom(newPosition);
  91672. };
  91673. return DecimationVertex;
  91674. }());
  91675. BABYLON.DecimationVertex = DecimationVertex;
  91676. var QuadraticMatrix = /** @class */ (function () {
  91677. function QuadraticMatrix(data) {
  91678. this.data = new Array(10);
  91679. for (var i = 0; i < 10; ++i) {
  91680. if (data && data[i]) {
  91681. this.data[i] = data[i];
  91682. }
  91683. else {
  91684. this.data[i] = 0;
  91685. }
  91686. }
  91687. }
  91688. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  91689. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  91690. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  91691. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  91692. return det;
  91693. };
  91694. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  91695. for (var i = 0; i < 10; ++i) {
  91696. this.data[i] += matrix.data[i];
  91697. }
  91698. };
  91699. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  91700. for (var i = 0; i < 10; ++i) {
  91701. this.data[i] += data[i];
  91702. }
  91703. };
  91704. QuadraticMatrix.prototype.add = function (matrix) {
  91705. var m = new QuadraticMatrix();
  91706. for (var i = 0; i < 10; ++i) {
  91707. m.data[i] = this.data[i] + matrix.data[i];
  91708. }
  91709. return m;
  91710. };
  91711. QuadraticMatrix.FromData = function (a, b, c, d) {
  91712. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  91713. };
  91714. //returning an array to avoid garbage collection
  91715. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  91716. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  91717. };
  91718. return QuadraticMatrix;
  91719. }());
  91720. BABYLON.QuadraticMatrix = QuadraticMatrix;
  91721. var Reference = /** @class */ (function () {
  91722. function Reference(vertexId, triangleId) {
  91723. this.vertexId = vertexId;
  91724. this.triangleId = triangleId;
  91725. }
  91726. return Reference;
  91727. }());
  91728. BABYLON.Reference = Reference;
  91729. /**
  91730. * An implementation of the Quadratic Error simplification algorithm.
  91731. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  91732. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  91733. * @author RaananW
  91734. */
  91735. var QuadraticErrorSimplification = /** @class */ (function () {
  91736. function QuadraticErrorSimplification(_mesh) {
  91737. this._mesh = _mesh;
  91738. this.syncIterations = 5000;
  91739. this.aggressiveness = 7;
  91740. this.decimationIterations = 100;
  91741. this.boundingBoxEpsilon = BABYLON.Epsilon;
  91742. }
  91743. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  91744. var _this = this;
  91745. this.initDecimatedMesh();
  91746. //iterating through the submeshes array, one after the other.
  91747. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  91748. _this.initWithMesh(loop.index, function () {
  91749. _this.runDecimation(settings, loop.index, function () {
  91750. loop.executeNext();
  91751. });
  91752. }, settings.optimizeMesh);
  91753. }, function () {
  91754. setTimeout(function () {
  91755. successCallback(_this._reconstructedMesh);
  91756. }, 0);
  91757. });
  91758. };
  91759. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  91760. var _this = this;
  91761. var targetCount = ~~(this.triangles.length * settings.quality);
  91762. var deletedTriangles = 0;
  91763. var triangleCount = this.triangles.length;
  91764. var iterationFunction = function (iteration, callback) {
  91765. setTimeout(function () {
  91766. if (iteration % 5 === 0) {
  91767. _this.updateMesh(iteration === 0);
  91768. }
  91769. for (var i = 0; i < _this.triangles.length; ++i) {
  91770. _this.triangles[i].isDirty = false;
  91771. }
  91772. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  91773. var trianglesIterator = function (i) {
  91774. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  91775. var t = _this.triangles[tIdx];
  91776. if (!t)
  91777. return;
  91778. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  91779. return;
  91780. }
  91781. for (var j = 0; j < 3; ++j) {
  91782. if (t.error[j] < threshold) {
  91783. var deleted0 = [];
  91784. var deleted1 = [];
  91785. var v0 = t.vertices[j];
  91786. var v1 = t.vertices[(j + 1) % 3];
  91787. if (v0.isBorder || v1.isBorder)
  91788. continue;
  91789. var p = BABYLON.Vector3.Zero();
  91790. var n = BABYLON.Vector3.Zero();
  91791. var uv = BABYLON.Vector2.Zero();
  91792. var color = new BABYLON.Color4(0, 0, 0, 1);
  91793. _this.calculateError(v0, v1, p, n, uv, color);
  91794. var delTr = new Array();
  91795. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  91796. continue;
  91797. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  91798. continue;
  91799. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  91800. continue;
  91801. var uniqueArray = new Array();
  91802. delTr.forEach(function (deletedT) {
  91803. if (uniqueArray.indexOf(deletedT) === -1) {
  91804. deletedT.deletePending = true;
  91805. uniqueArray.push(deletedT);
  91806. }
  91807. });
  91808. if (uniqueArray.length % 2 !== 0) {
  91809. continue;
  91810. }
  91811. v0.q = v1.q.add(v0.q);
  91812. v0.updatePosition(p);
  91813. var tStart = _this.references.length;
  91814. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  91815. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  91816. var tCount = _this.references.length - tStart;
  91817. if (tCount <= v0.triangleCount) {
  91818. if (tCount) {
  91819. for (var c = 0; c < tCount; c++) {
  91820. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  91821. }
  91822. }
  91823. }
  91824. else {
  91825. v0.triangleStart = tStart;
  91826. }
  91827. v0.triangleCount = tCount;
  91828. break;
  91829. }
  91830. }
  91831. };
  91832. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  91833. }, 0);
  91834. };
  91835. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  91836. if (triangleCount - deletedTriangles <= targetCount)
  91837. loop.breakLoop();
  91838. else {
  91839. iterationFunction(loop.index, function () {
  91840. loop.executeNext();
  91841. });
  91842. }
  91843. }, function () {
  91844. setTimeout(function () {
  91845. //reconstruct this part of the mesh
  91846. _this.reconstructMesh(submeshIndex);
  91847. successCallback();
  91848. }, 0);
  91849. });
  91850. };
  91851. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  91852. var _this = this;
  91853. this.vertices = [];
  91854. this.triangles = [];
  91855. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91856. var indices = this._mesh.getIndices();
  91857. var submesh = this._mesh.subMeshes[submeshIndex];
  91858. var findInVertices = function (positionToSearch) {
  91859. if (optimizeMesh) {
  91860. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  91861. if (_this.vertices[ii].position.equals(positionToSearch)) {
  91862. return _this.vertices[ii];
  91863. }
  91864. }
  91865. }
  91866. return null;
  91867. };
  91868. var vertexReferences = [];
  91869. var vertexInit = function (i) {
  91870. if (!positionData) {
  91871. return;
  91872. }
  91873. var offset = i + submesh.verticesStart;
  91874. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  91875. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  91876. vertex.originalOffsets.push(offset);
  91877. if (vertex.id === _this.vertices.length) {
  91878. _this.vertices.push(vertex);
  91879. }
  91880. vertexReferences.push(vertex.id);
  91881. };
  91882. //var totalVertices = mesh.getTotalVertices();
  91883. var totalVertices = submesh.verticesCount;
  91884. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  91885. var indicesInit = function (i) {
  91886. if (!indices) {
  91887. return;
  91888. }
  91889. var offset = (submesh.indexStart / 3) + i;
  91890. var pos = (offset * 3);
  91891. var i0 = indices[pos + 0];
  91892. var i1 = indices[pos + 1];
  91893. var i2 = indices[pos + 2];
  91894. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  91895. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  91896. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  91897. var triangle = new DecimationTriangle([v0, v1, v2]);
  91898. triangle.originalOffset = pos;
  91899. _this.triangles.push(triangle);
  91900. };
  91901. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  91902. _this.init(callback);
  91903. });
  91904. });
  91905. };
  91906. QuadraticErrorSimplification.prototype.init = function (callback) {
  91907. var _this = this;
  91908. var triangleInit1 = function (i) {
  91909. var t = _this.triangles[i];
  91910. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  91911. for (var j = 0; j < 3; j++) {
  91912. 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))));
  91913. }
  91914. };
  91915. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  91916. var triangleInit2 = function (i) {
  91917. var t = _this.triangles[i];
  91918. for (var j = 0; j < 3; ++j) {
  91919. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  91920. }
  91921. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  91922. };
  91923. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  91924. callback();
  91925. });
  91926. });
  91927. };
  91928. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  91929. var newTriangles = [];
  91930. var i;
  91931. for (i = 0; i < this.vertices.length; ++i) {
  91932. this.vertices[i].triangleCount = 0;
  91933. }
  91934. var t;
  91935. var j;
  91936. for (i = 0; i < this.triangles.length; ++i) {
  91937. if (!this.triangles[i].deleted) {
  91938. t = this.triangles[i];
  91939. for (j = 0; j < 3; ++j) {
  91940. t.vertices[j].triangleCount = 1;
  91941. }
  91942. newTriangles.push(t);
  91943. }
  91944. }
  91945. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  91946. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  91947. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  91948. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  91949. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  91950. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  91951. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  91952. var vertexCount = 0;
  91953. for (i = 0; i < this.vertices.length; ++i) {
  91954. var vertex = this.vertices[i];
  91955. vertex.id = vertexCount;
  91956. if (vertex.triangleCount) {
  91957. vertex.originalOffsets.forEach(function (originalOffset) {
  91958. if (!normalData) {
  91959. return;
  91960. }
  91961. newPositionData.push(vertex.position.x);
  91962. newPositionData.push(vertex.position.y);
  91963. newPositionData.push(vertex.position.z);
  91964. newNormalData.push(normalData[originalOffset * 3]);
  91965. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  91966. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  91967. if (uvs && uvs.length) {
  91968. newUVsData.push(uvs[(originalOffset * 2)]);
  91969. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  91970. }
  91971. else if (colorsData && colorsData.length) {
  91972. newColorsData.push(colorsData[(originalOffset * 4)]);
  91973. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  91974. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  91975. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  91976. }
  91977. ++vertexCount;
  91978. });
  91979. }
  91980. }
  91981. var startingIndex = this._reconstructedMesh.getTotalIndices();
  91982. var startingVertex = this._reconstructedMesh.getTotalVertices();
  91983. var submeshesArray = this._reconstructedMesh.subMeshes;
  91984. this._reconstructedMesh.subMeshes = [];
  91985. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  91986. var originalIndices = this._mesh.getIndices();
  91987. for (i = 0; i < newTriangles.length; ++i) {
  91988. t = newTriangles[i]; //now get the new referencing point for each vertex
  91989. [0, 1, 2].forEach(function (idx) {
  91990. var id = originalIndices[t.originalOffset + idx];
  91991. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  91992. if (offset < 0)
  91993. offset = 0;
  91994. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  91995. });
  91996. }
  91997. //overwriting the old vertex buffers and indices.
  91998. this._reconstructedMesh.setIndices(newIndicesArray);
  91999. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  92000. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  92001. if (newUVsData.length > 0)
  92002. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  92003. if (newColorsData.length > 0)
  92004. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  92005. //create submesh
  92006. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  92007. if (submeshIndex > 0) {
  92008. this._reconstructedMesh.subMeshes = [];
  92009. submeshesArray.forEach(function (submesh) {
  92010. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  92011. });
  92012. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  92013. }
  92014. };
  92015. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  92016. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  92017. this._reconstructedMesh.material = this._mesh.material;
  92018. this._reconstructedMesh.parent = this._mesh.parent;
  92019. this._reconstructedMesh.isVisible = false;
  92020. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  92021. };
  92022. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  92023. for (var i = 0; i < vertex1.triangleCount; ++i) {
  92024. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  92025. if (t.deleted)
  92026. continue;
  92027. var s = this.references[vertex1.triangleStart + i].vertexId;
  92028. var v1 = t.vertices[(s + 1) % 3];
  92029. var v2 = t.vertices[(s + 2) % 3];
  92030. if ((v1 === vertex2 || v2 === vertex2)) {
  92031. deletedArray[i] = true;
  92032. delTr.push(t);
  92033. continue;
  92034. }
  92035. var d1 = v1.position.subtract(point);
  92036. d1 = d1.normalize();
  92037. var d2 = v2.position.subtract(point);
  92038. d2 = d2.normalize();
  92039. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  92040. return true;
  92041. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  92042. deletedArray[i] = false;
  92043. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  92044. return true;
  92045. }
  92046. return false;
  92047. };
  92048. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  92049. var newDeleted = deletedTriangles;
  92050. for (var i = 0; i < vertex.triangleCount; ++i) {
  92051. var ref = this.references[vertex.triangleStart + i];
  92052. var t = this.triangles[ref.triangleId];
  92053. if (t.deleted)
  92054. continue;
  92055. if (deletedArray[i] && t.deletePending) {
  92056. t.deleted = true;
  92057. newDeleted++;
  92058. continue;
  92059. }
  92060. t.vertices[ref.vertexId] = origVertex;
  92061. t.isDirty = true;
  92062. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  92063. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  92064. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  92065. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  92066. this.references.push(ref);
  92067. }
  92068. return newDeleted;
  92069. };
  92070. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  92071. for (var i = 0; i < this.vertices.length; ++i) {
  92072. var vCount = [];
  92073. var vId = [];
  92074. var v = this.vertices[i];
  92075. var j;
  92076. for (j = 0; j < v.triangleCount; ++j) {
  92077. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  92078. for (var ii = 0; ii < 3; ii++) {
  92079. var ofs = 0;
  92080. var vv = triangle.vertices[ii];
  92081. while (ofs < vCount.length) {
  92082. if (vId[ofs] === vv.id)
  92083. break;
  92084. ++ofs;
  92085. }
  92086. if (ofs === vCount.length) {
  92087. vCount.push(1);
  92088. vId.push(vv.id);
  92089. }
  92090. else {
  92091. vCount[ofs]++;
  92092. }
  92093. }
  92094. }
  92095. for (j = 0; j < vCount.length; ++j) {
  92096. if (vCount[j] === 1) {
  92097. this.vertices[vId[j]].isBorder = true;
  92098. }
  92099. else {
  92100. this.vertices[vId[j]].isBorder = false;
  92101. }
  92102. }
  92103. }
  92104. };
  92105. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  92106. if (identifyBorders === void 0) { identifyBorders = false; }
  92107. var i;
  92108. if (!identifyBorders) {
  92109. var newTrianglesVector = [];
  92110. for (i = 0; i < this.triangles.length; ++i) {
  92111. if (!this.triangles[i].deleted) {
  92112. newTrianglesVector.push(this.triangles[i]);
  92113. }
  92114. }
  92115. this.triangles = newTrianglesVector;
  92116. }
  92117. for (i = 0; i < this.vertices.length; ++i) {
  92118. this.vertices[i].triangleCount = 0;
  92119. this.vertices[i].triangleStart = 0;
  92120. }
  92121. var t;
  92122. var j;
  92123. var v;
  92124. for (i = 0; i < this.triangles.length; ++i) {
  92125. t = this.triangles[i];
  92126. for (j = 0; j < 3; ++j) {
  92127. v = t.vertices[j];
  92128. v.triangleCount++;
  92129. }
  92130. }
  92131. var tStart = 0;
  92132. for (i = 0; i < this.vertices.length; ++i) {
  92133. this.vertices[i].triangleStart = tStart;
  92134. tStart += this.vertices[i].triangleCount;
  92135. this.vertices[i].triangleCount = 0;
  92136. }
  92137. var newReferences = new Array(this.triangles.length * 3);
  92138. for (i = 0; i < this.triangles.length; ++i) {
  92139. t = this.triangles[i];
  92140. for (j = 0; j < 3; ++j) {
  92141. v = t.vertices[j];
  92142. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  92143. v.triangleCount++;
  92144. }
  92145. }
  92146. this.references = newReferences;
  92147. if (identifyBorders) {
  92148. this.identifyBorder();
  92149. }
  92150. };
  92151. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  92152. var x = point.x;
  92153. var y = point.y;
  92154. var z = point.z;
  92155. 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
  92156. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  92157. };
  92158. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  92159. var q = vertex1.q.add(vertex2.q);
  92160. var border = vertex1.isBorder && vertex2.isBorder;
  92161. var error = 0;
  92162. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  92163. if (qDet !== 0 && !border) {
  92164. if (!pointResult) {
  92165. pointResult = BABYLON.Vector3.Zero();
  92166. }
  92167. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  92168. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  92169. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  92170. error = this.vertexError(q, pointResult);
  92171. }
  92172. else {
  92173. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  92174. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  92175. var error1 = this.vertexError(q, vertex1.position);
  92176. var error2 = this.vertexError(q, vertex2.position);
  92177. var error3 = this.vertexError(q, p3);
  92178. error = Math.min(error1, error2, error3);
  92179. if (error === error1) {
  92180. if (pointResult) {
  92181. pointResult.copyFrom(vertex1.position);
  92182. }
  92183. }
  92184. else if (error === error2) {
  92185. if (pointResult) {
  92186. pointResult.copyFrom(vertex2.position);
  92187. }
  92188. }
  92189. else {
  92190. if (pointResult) {
  92191. pointResult.copyFrom(p3);
  92192. }
  92193. }
  92194. }
  92195. return error;
  92196. };
  92197. return QuadraticErrorSimplification;
  92198. }());
  92199. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  92200. })(BABYLON || (BABYLON = {}));
  92201. //# sourceMappingURL=babylon.meshSimplification.js.map
  92202. var BABYLON;
  92203. (function (BABYLON) {
  92204. var MeshLODLevel = /** @class */ (function () {
  92205. function MeshLODLevel(distance, mesh) {
  92206. this.distance = distance;
  92207. this.mesh = mesh;
  92208. }
  92209. return MeshLODLevel;
  92210. }());
  92211. BABYLON.MeshLODLevel = MeshLODLevel;
  92212. })(BABYLON || (BABYLON = {}));
  92213. //# sourceMappingURL=babylon.meshLODLevel.js.map
  92214. var BABYLON;
  92215. (function (BABYLON) {
  92216. /**
  92217. * Defines the root class used to create scene optimization to use with SceneOptimizer
  92218. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92219. */
  92220. var SceneOptimization = /** @class */ (function () {
  92221. /**
  92222. * Creates the SceneOptimization object
  92223. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92224. * @param desc defines the description associated with the optimization
  92225. */
  92226. function SceneOptimization(
  92227. /**
  92228. * Defines the priority of this optimization (0 by default which means first in the list)
  92229. */
  92230. priority) {
  92231. if (priority === void 0) { priority = 0; }
  92232. this.priority = priority;
  92233. }
  92234. /**
  92235. * Gets a string describing the action executed by the current optimization
  92236. * @returns description string
  92237. */
  92238. SceneOptimization.prototype.getDescription = function () {
  92239. return "";
  92240. };
  92241. /**
  92242. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92243. * @param scene defines the current scene where to apply this optimization
  92244. * @param optimizer defines the current optimizer
  92245. * @returns true if everything that can be done was applied
  92246. */
  92247. SceneOptimization.prototype.apply = function (scene, optimizer) {
  92248. return true;
  92249. };
  92250. ;
  92251. return SceneOptimization;
  92252. }());
  92253. BABYLON.SceneOptimization = SceneOptimization;
  92254. /**
  92255. * Defines an optimization used to reduce the size of render target textures
  92256. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92257. */
  92258. var TextureOptimization = /** @class */ (function (_super) {
  92259. __extends(TextureOptimization, _super);
  92260. /**
  92261. * Creates the TextureOptimization object
  92262. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92263. * @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
  92264. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92265. */
  92266. function TextureOptimization(
  92267. /**
  92268. * Defines the priority of this optimization (0 by default which means first in the list)
  92269. */
  92270. priority,
  92271. /**
  92272. * 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
  92273. */
  92274. maximumSize,
  92275. /**
  92276. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  92277. */
  92278. step) {
  92279. if (priority === void 0) { priority = 0; }
  92280. if (maximumSize === void 0) { maximumSize = 1024; }
  92281. if (step === void 0) { step = 0.5; }
  92282. var _this = _super.call(this, priority) || this;
  92283. _this.priority = priority;
  92284. _this.maximumSize = maximumSize;
  92285. _this.step = step;
  92286. return _this;
  92287. }
  92288. /**
  92289. * Gets a string describing the action executed by the current optimization
  92290. * @returns description string
  92291. */
  92292. TextureOptimization.prototype.getDescription = function () {
  92293. return "Reducing render target texture size to " + this.maximumSize;
  92294. };
  92295. /**
  92296. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92297. * @param scene defines the current scene where to apply this optimization
  92298. * @param optimizer defines the current optimizer
  92299. * @returns true if everything that can be done was applied
  92300. */
  92301. TextureOptimization.prototype.apply = function (scene, optimizer) {
  92302. var allDone = true;
  92303. for (var index = 0; index < scene.textures.length; index++) {
  92304. var texture = scene.textures[index];
  92305. if (!texture.canRescale || texture.getContext) {
  92306. continue;
  92307. }
  92308. var currentSize = texture.getSize();
  92309. var maxDimension = Math.max(currentSize.width, currentSize.height);
  92310. if (maxDimension > this.maximumSize) {
  92311. texture.scale(this.step);
  92312. allDone = false;
  92313. }
  92314. }
  92315. return allDone;
  92316. };
  92317. return TextureOptimization;
  92318. }(SceneOptimization));
  92319. BABYLON.TextureOptimization = TextureOptimization;
  92320. /**
  92321. * Defines an optimization used to increase or decrease the rendering resolution
  92322. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92323. */
  92324. var HardwareScalingOptimization = /** @class */ (function (_super) {
  92325. __extends(HardwareScalingOptimization, _super);
  92326. /**
  92327. * Creates the HardwareScalingOptimization object
  92328. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92329. * @param maximumScale defines the maximum scale to use (2 by default)
  92330. * @param step defines the step to use between two passes (0.5 by default)
  92331. */
  92332. function HardwareScalingOptimization(
  92333. /**
  92334. * Defines the priority of this optimization (0 by default which means first in the list)
  92335. */
  92336. priority,
  92337. /**
  92338. * Defines the maximum scale to use (2 by default)
  92339. */
  92340. maximumScale,
  92341. /**
  92342. * Defines the step to use between two passes (0.5 by default)
  92343. */
  92344. step) {
  92345. if (priority === void 0) { priority = 0; }
  92346. if (maximumScale === void 0) { maximumScale = 2; }
  92347. if (step === void 0) { step = 0.25; }
  92348. var _this = _super.call(this, priority) || this;
  92349. _this.priority = priority;
  92350. _this.maximumScale = maximumScale;
  92351. _this.step = step;
  92352. _this._currentScale = -1;
  92353. _this._directionOffset = 1;
  92354. return _this;
  92355. }
  92356. /**
  92357. * Gets a string describing the action executed by the current optimization
  92358. * @return description string
  92359. */
  92360. HardwareScalingOptimization.prototype.getDescription = function () {
  92361. return "Setting hardware scaling level to " + this._currentScale;
  92362. };
  92363. /**
  92364. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92365. * @param scene defines the current scene where to apply this optimization
  92366. * @param optimizer defines the current optimizer
  92367. * @returns true if everything that can be done was applied
  92368. */
  92369. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  92370. if (this._currentScale === -1) {
  92371. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  92372. if (this._currentScale > this.maximumScale) {
  92373. this._directionOffset = -1;
  92374. }
  92375. }
  92376. this._currentScale += this._directionOffset * this.step;
  92377. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  92378. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  92379. };
  92380. ;
  92381. return HardwareScalingOptimization;
  92382. }(SceneOptimization));
  92383. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  92384. /**
  92385. * Defines an optimization used to remove shadows
  92386. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92387. */
  92388. var ShadowsOptimization = /** @class */ (function (_super) {
  92389. __extends(ShadowsOptimization, _super);
  92390. function ShadowsOptimization() {
  92391. return _super !== null && _super.apply(this, arguments) || this;
  92392. }
  92393. /**
  92394. * Gets a string describing the action executed by the current optimization
  92395. * @return description string
  92396. */
  92397. ShadowsOptimization.prototype.getDescription = function () {
  92398. return "Turning shadows on/off";
  92399. };
  92400. /**
  92401. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92402. * @param scene defines the current scene where to apply this optimization
  92403. * @param optimizer defines the current optimizer
  92404. * @returns true if everything that can be done was applied
  92405. */
  92406. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  92407. scene.shadowsEnabled = optimizer.isInImprovementMode;
  92408. return true;
  92409. };
  92410. ;
  92411. return ShadowsOptimization;
  92412. }(SceneOptimization));
  92413. BABYLON.ShadowsOptimization = ShadowsOptimization;
  92414. /**
  92415. * Defines an optimization used to turn post-processes off
  92416. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92417. */
  92418. var PostProcessesOptimization = /** @class */ (function (_super) {
  92419. __extends(PostProcessesOptimization, _super);
  92420. function PostProcessesOptimization() {
  92421. return _super !== null && _super.apply(this, arguments) || this;
  92422. }
  92423. /**
  92424. * Gets a string describing the action executed by the current optimization
  92425. * @return description string
  92426. */
  92427. PostProcessesOptimization.prototype.getDescription = function () {
  92428. return "Turning post-processes on/off";
  92429. };
  92430. /**
  92431. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92432. * @param scene defines the current scene where to apply this optimization
  92433. * @param optimizer defines the current optimizer
  92434. * @returns true if everything that can be done was applied
  92435. */
  92436. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  92437. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  92438. return true;
  92439. };
  92440. ;
  92441. return PostProcessesOptimization;
  92442. }(SceneOptimization));
  92443. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  92444. /**
  92445. * Defines an optimization used to turn lens flares off
  92446. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92447. */
  92448. var LensFlaresOptimization = /** @class */ (function (_super) {
  92449. __extends(LensFlaresOptimization, _super);
  92450. function LensFlaresOptimization() {
  92451. return _super !== null && _super.apply(this, arguments) || this;
  92452. }
  92453. /**
  92454. * Gets a string describing the action executed by the current optimization
  92455. * @return description string
  92456. */
  92457. LensFlaresOptimization.prototype.getDescription = function () {
  92458. return "Turning lens flares on/off";
  92459. };
  92460. /**
  92461. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92462. * @param scene defines the current scene where to apply this optimization
  92463. * @param optimizer defines the current optimizer
  92464. * @returns true if everything that can be done was applied
  92465. */
  92466. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  92467. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  92468. return true;
  92469. };
  92470. ;
  92471. return LensFlaresOptimization;
  92472. }(SceneOptimization));
  92473. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  92474. /**
  92475. * Defines an optimization based on user defined callback.
  92476. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92477. */
  92478. var CustomOptimization = /** @class */ (function (_super) {
  92479. __extends(CustomOptimization, _super);
  92480. function CustomOptimization() {
  92481. return _super !== null && _super.apply(this, arguments) || this;
  92482. }
  92483. /**
  92484. * Gets a string describing the action executed by the current optimization
  92485. * @returns description string
  92486. */
  92487. CustomOptimization.prototype.getDescription = function () {
  92488. if (this.onGetDescription) {
  92489. return this.onGetDescription();
  92490. }
  92491. return "Running user defined callback";
  92492. };
  92493. /**
  92494. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92495. * @param scene defines the current scene where to apply this optimization
  92496. * @param optimizer defines the current optimizer
  92497. * @returns true if everything that can be done was applied
  92498. */
  92499. CustomOptimization.prototype.apply = function (scene, optimizer) {
  92500. if (this.onApply) {
  92501. return this.onApply(scene, optimizer);
  92502. }
  92503. return true;
  92504. };
  92505. ;
  92506. return CustomOptimization;
  92507. }(SceneOptimization));
  92508. BABYLON.CustomOptimization = CustomOptimization;
  92509. /**
  92510. * Defines an optimization used to turn particles off
  92511. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92512. */
  92513. var ParticlesOptimization = /** @class */ (function (_super) {
  92514. __extends(ParticlesOptimization, _super);
  92515. function ParticlesOptimization() {
  92516. return _super !== null && _super.apply(this, arguments) || this;
  92517. }
  92518. /**
  92519. * Gets a string describing the action executed by the current optimization
  92520. * @return description string
  92521. */
  92522. ParticlesOptimization.prototype.getDescription = function () {
  92523. return "Turning particles on/off";
  92524. };
  92525. /**
  92526. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92527. * @param scene defines the current scene where to apply this optimization
  92528. * @param optimizer defines the current optimizer
  92529. * @returns true if everything that can be done was applied
  92530. */
  92531. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  92532. scene.particlesEnabled = optimizer.isInImprovementMode;
  92533. return true;
  92534. };
  92535. ;
  92536. return ParticlesOptimization;
  92537. }(SceneOptimization));
  92538. BABYLON.ParticlesOptimization = ParticlesOptimization;
  92539. /**
  92540. * Defines an optimization used to turn render targets off
  92541. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92542. */
  92543. var RenderTargetsOptimization = /** @class */ (function (_super) {
  92544. __extends(RenderTargetsOptimization, _super);
  92545. function RenderTargetsOptimization() {
  92546. return _super !== null && _super.apply(this, arguments) || this;
  92547. }
  92548. /**
  92549. * Gets a string describing the action executed by the current optimization
  92550. * @return description string
  92551. */
  92552. RenderTargetsOptimization.prototype.getDescription = function () {
  92553. return "Turning render targets off";
  92554. };
  92555. /**
  92556. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92557. * @param scene defines the current scene where to apply this optimization
  92558. * @param optimizer defines the current optimizer
  92559. * @returns true if everything that can be done was applied
  92560. */
  92561. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  92562. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  92563. return true;
  92564. };
  92565. ;
  92566. return RenderTargetsOptimization;
  92567. }(SceneOptimization));
  92568. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  92569. /**
  92570. * Defines an optimization used to merge meshes with compatible materials
  92571. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92572. */
  92573. var MergeMeshesOptimization = /** @class */ (function (_super) {
  92574. __extends(MergeMeshesOptimization, _super);
  92575. function MergeMeshesOptimization() {
  92576. var _this = _super !== null && _super.apply(this, arguments) || this;
  92577. _this._canBeMerged = function (abstractMesh) {
  92578. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  92579. return false;
  92580. }
  92581. var mesh = abstractMesh;
  92582. if (!mesh.isVisible || !mesh.isEnabled()) {
  92583. return false;
  92584. }
  92585. if (mesh.instances.length > 0) {
  92586. return false;
  92587. }
  92588. if (mesh.skeleton || mesh.hasLODLevels) {
  92589. return false;
  92590. }
  92591. if (mesh.parent) {
  92592. return false;
  92593. }
  92594. return true;
  92595. };
  92596. return _this;
  92597. }
  92598. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  92599. /**
  92600. * Gets or sets a boolean which defines if optimization octree has to be updated
  92601. */
  92602. get: function () {
  92603. return MergeMeshesOptimization._UpdateSelectionTree;
  92604. },
  92605. /**
  92606. * Gets or sets a boolean which defines if optimization octree has to be updated
  92607. */
  92608. set: function (value) {
  92609. MergeMeshesOptimization._UpdateSelectionTree = value;
  92610. },
  92611. enumerable: true,
  92612. configurable: true
  92613. });
  92614. /**
  92615. * Gets a string describing the action executed by the current optimization
  92616. * @return description string
  92617. */
  92618. MergeMeshesOptimization.prototype.getDescription = function () {
  92619. return "Merging similar meshes together";
  92620. };
  92621. /**
  92622. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  92623. * @param scene defines the current scene where to apply this optimization
  92624. * @param optimizer defines the current optimizer
  92625. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  92626. * @returns true if everything that can be done was applied
  92627. */
  92628. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  92629. var globalPool = scene.meshes.slice(0);
  92630. var globalLength = globalPool.length;
  92631. for (var index = 0; index < globalLength; index++) {
  92632. var currentPool = new Array();
  92633. var current = globalPool[index];
  92634. // Checks
  92635. if (!this._canBeMerged(current)) {
  92636. continue;
  92637. }
  92638. currentPool.push(current);
  92639. // Find compatible meshes
  92640. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  92641. var otherMesh = globalPool[subIndex];
  92642. if (!this._canBeMerged(otherMesh)) {
  92643. continue;
  92644. }
  92645. if (otherMesh.material !== current.material) {
  92646. continue;
  92647. }
  92648. if (otherMesh.checkCollisions !== current.checkCollisions) {
  92649. continue;
  92650. }
  92651. currentPool.push(otherMesh);
  92652. globalLength--;
  92653. globalPool.splice(subIndex, 1);
  92654. subIndex--;
  92655. }
  92656. if (currentPool.length < 2) {
  92657. continue;
  92658. }
  92659. // Merge meshes
  92660. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  92661. }
  92662. if (updateSelectionTree != undefined) {
  92663. if (updateSelectionTree) {
  92664. scene.createOrUpdateSelectionOctree();
  92665. }
  92666. }
  92667. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  92668. scene.createOrUpdateSelectionOctree();
  92669. }
  92670. return true;
  92671. };
  92672. ;
  92673. MergeMeshesOptimization._UpdateSelectionTree = false;
  92674. return MergeMeshesOptimization;
  92675. }(SceneOptimization));
  92676. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  92677. /**
  92678. * Defines a list of options used by SceneOptimizer
  92679. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92680. */
  92681. var SceneOptimizerOptions = /** @class */ (function () {
  92682. /**
  92683. * Creates a new list of options used by SceneOptimizer
  92684. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  92685. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  92686. */
  92687. function SceneOptimizerOptions(
  92688. /**
  92689. * Defines the target frame rate to reach (60 by default)
  92690. */
  92691. targetFrameRate,
  92692. /**
  92693. * Defines the interval between two checkes (2000ms by default)
  92694. */
  92695. trackerDuration) {
  92696. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  92697. if (trackerDuration === void 0) { trackerDuration = 2000; }
  92698. this.targetFrameRate = targetFrameRate;
  92699. this.trackerDuration = trackerDuration;
  92700. /**
  92701. * Gets the list of optimizations to apply
  92702. */
  92703. this.optimizations = new Array();
  92704. }
  92705. /**
  92706. * Add a new optimization
  92707. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  92708. * @returns the current SceneOptimizerOptions
  92709. */
  92710. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  92711. this.optimizations.push(optimization);
  92712. return this;
  92713. };
  92714. /**
  92715. * Add a new custom optimization
  92716. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  92717. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  92718. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92719. * @returns the current SceneOptimizerOptions
  92720. */
  92721. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  92722. if (priority === void 0) { priority = 0; }
  92723. var optimization = new CustomOptimization(priority);
  92724. optimization.onApply = onApply;
  92725. optimization.onGetDescription = onGetDescription;
  92726. this.optimizations.push(optimization);
  92727. return this;
  92728. };
  92729. /**
  92730. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  92731. * @param targetFrameRate defines the target frame rate (60 by default)
  92732. * @returns a SceneOptimizerOptions object
  92733. */
  92734. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  92735. var result = new SceneOptimizerOptions(targetFrameRate);
  92736. var priority = 0;
  92737. result.addOptimization(new MergeMeshesOptimization(priority));
  92738. result.addOptimization(new ShadowsOptimization(priority));
  92739. result.addOptimization(new LensFlaresOptimization(priority));
  92740. // Next priority
  92741. priority++;
  92742. result.addOptimization(new PostProcessesOptimization(priority));
  92743. result.addOptimization(new ParticlesOptimization(priority));
  92744. // Next priority
  92745. priority++;
  92746. result.addOptimization(new TextureOptimization(priority, 1024));
  92747. return result;
  92748. };
  92749. /**
  92750. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  92751. * @param targetFrameRate defines the target frame rate (60 by default)
  92752. * @returns a SceneOptimizerOptions object
  92753. */
  92754. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  92755. var result = new SceneOptimizerOptions(targetFrameRate);
  92756. var priority = 0;
  92757. result.addOptimization(new MergeMeshesOptimization(priority));
  92758. result.addOptimization(new ShadowsOptimization(priority));
  92759. result.addOptimization(new LensFlaresOptimization(priority));
  92760. // Next priority
  92761. priority++;
  92762. result.addOptimization(new PostProcessesOptimization(priority));
  92763. result.addOptimization(new ParticlesOptimization(priority));
  92764. // Next priority
  92765. priority++;
  92766. result.addOptimization(new TextureOptimization(priority, 512));
  92767. // Next priority
  92768. priority++;
  92769. result.addOptimization(new RenderTargetsOptimization(priority));
  92770. // Next priority
  92771. priority++;
  92772. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  92773. return result;
  92774. };
  92775. /**
  92776. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  92777. * @param targetFrameRate defines the target frame rate (60 by default)
  92778. * @returns a SceneOptimizerOptions object
  92779. */
  92780. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  92781. var result = new SceneOptimizerOptions(targetFrameRate);
  92782. var priority = 0;
  92783. result.addOptimization(new MergeMeshesOptimization(priority));
  92784. result.addOptimization(new ShadowsOptimization(priority));
  92785. result.addOptimization(new LensFlaresOptimization(priority));
  92786. // Next priority
  92787. priority++;
  92788. result.addOptimization(new PostProcessesOptimization(priority));
  92789. result.addOptimization(new ParticlesOptimization(priority));
  92790. // Next priority
  92791. priority++;
  92792. result.addOptimization(new TextureOptimization(priority, 256));
  92793. // Next priority
  92794. priority++;
  92795. result.addOptimization(new RenderTargetsOptimization(priority));
  92796. // Next priority
  92797. priority++;
  92798. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  92799. return result;
  92800. };
  92801. return SceneOptimizerOptions;
  92802. }());
  92803. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  92804. /**
  92805. * Class used to run optimizations in order to reach a target frame rate
  92806. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92807. */
  92808. var SceneOptimizer = /** @class */ (function () {
  92809. /**
  92810. * Creates a new SceneOptimizer
  92811. * @param scene defines the scene to work on
  92812. * @param options defines the options to use with the SceneOptimizer
  92813. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  92814. * @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)
  92815. */
  92816. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  92817. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  92818. if (improvementMode === void 0) { improvementMode = false; }
  92819. var _this = this;
  92820. this._isRunning = false;
  92821. this._currentPriorityLevel = 0;
  92822. this._targetFrameRate = 60;
  92823. this._trackerDuration = 2000;
  92824. this._currentFrameRate = 0;
  92825. this._improvementMode = false;
  92826. /**
  92827. * Defines an observable called when the optimizer reaches the target frame rate
  92828. */
  92829. this.onSuccessObservable = new BABYLON.Observable();
  92830. /**
  92831. * Defines an observable called when the optimizer enables an optimization
  92832. */
  92833. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  92834. /**
  92835. * Defines an observable called when the optimizer is not able to reach the target frame rate
  92836. */
  92837. this.onFailureObservable = new BABYLON.Observable();
  92838. if (!options) {
  92839. this._options = new SceneOptimizerOptions();
  92840. }
  92841. else {
  92842. this._options = options;
  92843. }
  92844. if (this._options.targetFrameRate) {
  92845. this._targetFrameRate = this._options.targetFrameRate;
  92846. }
  92847. if (this._options.trackerDuration) {
  92848. this._trackerDuration = this._options.trackerDuration;
  92849. }
  92850. if (autoGeneratePriorities) {
  92851. var priority = 0;
  92852. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  92853. var optim = _a[_i];
  92854. optim.priority = priority++;
  92855. }
  92856. }
  92857. this._improvementMode = improvementMode;
  92858. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92859. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  92860. _this._sceneDisposeObserver = null;
  92861. _this.dispose();
  92862. });
  92863. }
  92864. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  92865. /**
  92866. * Gets a boolean indicating if the optimizer is in improvement mode
  92867. */
  92868. get: function () {
  92869. return this._improvementMode;
  92870. },
  92871. enumerable: true,
  92872. configurable: true
  92873. });
  92874. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  92875. /**
  92876. * Gets the current priority level (0 at start)
  92877. */
  92878. get: function () {
  92879. return this._currentPriorityLevel;
  92880. },
  92881. enumerable: true,
  92882. configurable: true
  92883. });
  92884. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  92885. /**
  92886. * Gets the current frame rate checked by the SceneOptimizer
  92887. */
  92888. get: function () {
  92889. return this._currentFrameRate;
  92890. },
  92891. enumerable: true,
  92892. configurable: true
  92893. });
  92894. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  92895. /**
  92896. * Gets or sets the current target frame rate (60 by default)
  92897. */
  92898. get: function () {
  92899. return this._targetFrameRate;
  92900. },
  92901. /**
  92902. * Gets or sets the current target frame rate (60 by default)
  92903. */
  92904. set: function (value) {
  92905. this._targetFrameRate = value;
  92906. },
  92907. enumerable: true,
  92908. configurable: true
  92909. });
  92910. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  92911. /**
  92912. * Gets or sets the current interval between two checks (every 2000ms by default)
  92913. */
  92914. get: function () {
  92915. return this._trackerDuration;
  92916. },
  92917. /**
  92918. * Gets or sets the current interval between two checks (every 2000ms by default)
  92919. */
  92920. set: function (value) {
  92921. this._trackerDuration = value;
  92922. },
  92923. enumerable: true,
  92924. configurable: true
  92925. });
  92926. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  92927. /**
  92928. * Gets the list of active optimizations
  92929. */
  92930. get: function () {
  92931. return this._options.optimizations;
  92932. },
  92933. enumerable: true,
  92934. configurable: true
  92935. });
  92936. /**
  92937. * Stops the current optimizer
  92938. */
  92939. SceneOptimizer.prototype.stop = function () {
  92940. this._isRunning = false;
  92941. };
  92942. /**
  92943. * Reset the optimizer to initial step (current priority level = 0)
  92944. */
  92945. SceneOptimizer.prototype.reset = function () {
  92946. this._currentPriorityLevel = 0;
  92947. };
  92948. /**
  92949. * Start the optimizer. By default it will try to reach a specific framerate
  92950. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  92951. */
  92952. SceneOptimizer.prototype.start = function () {
  92953. var _this = this;
  92954. if (this._isRunning) {
  92955. return;
  92956. }
  92957. this._isRunning = true;
  92958. // Let's wait for the scene to be ready before running our check
  92959. this._scene.executeWhenReady(function () {
  92960. setTimeout(function () {
  92961. _this._checkCurrentState();
  92962. }, _this._trackerDuration);
  92963. });
  92964. };
  92965. SceneOptimizer.prototype._checkCurrentState = function () {
  92966. var _this = this;
  92967. if (!this._isRunning) {
  92968. return;
  92969. }
  92970. var scene = this._scene;
  92971. var options = this._options;
  92972. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  92973. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  92974. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  92975. this._isRunning = false;
  92976. this.onSuccessObservable.notifyObservers(this);
  92977. return;
  92978. }
  92979. // Apply current level of optimizations
  92980. var allDone = true;
  92981. var noOptimizationApplied = true;
  92982. for (var index = 0; index < options.optimizations.length; index++) {
  92983. var optimization = options.optimizations[index];
  92984. if (optimization.priority === this._currentPriorityLevel) {
  92985. noOptimizationApplied = false;
  92986. allDone = allDone && optimization.apply(scene, this);
  92987. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  92988. }
  92989. }
  92990. // If no optimization was applied, this is a failure :(
  92991. if (noOptimizationApplied) {
  92992. this._isRunning = false;
  92993. this.onFailureObservable.notifyObservers(this);
  92994. return;
  92995. }
  92996. // If all optimizations were done, move to next level
  92997. if (allDone) {
  92998. this._currentPriorityLevel++;
  92999. }
  93000. // Let's the system running for a specific amount of time before checking FPS
  93001. scene.executeWhenReady(function () {
  93002. setTimeout(function () {
  93003. _this._checkCurrentState();
  93004. }, _this._trackerDuration);
  93005. });
  93006. };
  93007. /**
  93008. * Release all resources
  93009. */
  93010. SceneOptimizer.prototype.dispose = function () {
  93011. this.stop();
  93012. this.onSuccessObservable.clear();
  93013. this.onFailureObservable.clear();
  93014. this.onNewOptimizationAppliedObservable.clear();
  93015. if (this._sceneDisposeObserver) {
  93016. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  93017. }
  93018. };
  93019. /**
  93020. * Helper function to create a SceneOptimizer with one single line of code
  93021. * @param scene defines the scene to work on
  93022. * @param options defines the options to use with the SceneOptimizer
  93023. * @param onSuccess defines a callback to call on success
  93024. * @param onFailure defines a callback to call on failure
  93025. * @returns the new SceneOptimizer object
  93026. */
  93027. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  93028. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  93029. if (onSuccess) {
  93030. optimizer.onSuccessObservable.add(function () {
  93031. onSuccess();
  93032. });
  93033. }
  93034. if (onFailure) {
  93035. optimizer.onFailureObservable.add(function () {
  93036. onFailure();
  93037. });
  93038. }
  93039. optimizer.start();
  93040. return optimizer;
  93041. };
  93042. return SceneOptimizer;
  93043. }());
  93044. BABYLON.SceneOptimizer = SceneOptimizer;
  93045. })(BABYLON || (BABYLON = {}));
  93046. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  93047. var BABYLON;
  93048. (function (BABYLON) {
  93049. var OutlineRenderer = /** @class */ (function () {
  93050. function OutlineRenderer(scene) {
  93051. this.zOffset = 1;
  93052. this._scene = scene;
  93053. }
  93054. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  93055. var _this = this;
  93056. if (useOverlay === void 0) { useOverlay = false; }
  93057. var scene = this._scene;
  93058. var engine = this._scene.getEngine();
  93059. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93060. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  93061. return;
  93062. }
  93063. var mesh = subMesh.getRenderingMesh();
  93064. var material = subMesh.getMaterial();
  93065. if (!material || !scene.activeCamera) {
  93066. return;
  93067. }
  93068. engine.enableEffect(this._effect);
  93069. // Logarithmic depth
  93070. if (material.useLogarithmicDepth) {
  93071. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  93072. }
  93073. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  93074. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  93075. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  93076. // Bones
  93077. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93078. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93079. }
  93080. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  93081. // Alpha test
  93082. if (material && material.needAlphaTesting()) {
  93083. var alphaTexture = material.getAlphaTestTexture();
  93084. if (alphaTexture) {
  93085. this._effect.setTexture("diffuseSampler", alphaTexture);
  93086. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  93087. }
  93088. }
  93089. engine.setZOffset(-this.zOffset);
  93090. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  93091. engine.setZOffset(0);
  93092. };
  93093. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  93094. var defines = [];
  93095. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  93096. var mesh = subMesh.getMesh();
  93097. var material = subMesh.getMaterial();
  93098. if (material) {
  93099. // Alpha test
  93100. if (material.needAlphaTesting()) {
  93101. defines.push("#define ALPHATEST");
  93102. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93103. attribs.push(BABYLON.VertexBuffer.UVKind);
  93104. defines.push("#define UV1");
  93105. }
  93106. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  93107. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93108. defines.push("#define UV2");
  93109. }
  93110. }
  93111. //Logarithmic depth
  93112. if (material.useLogarithmicDepth) {
  93113. defines.push("#define LOGARITHMICDEPTH");
  93114. }
  93115. }
  93116. // Bones
  93117. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93118. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93119. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93120. if (mesh.numBoneInfluencers > 4) {
  93121. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93122. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93123. }
  93124. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93125. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  93126. }
  93127. else {
  93128. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93129. }
  93130. // Instances
  93131. if (useInstances) {
  93132. defines.push("#define INSTANCES");
  93133. attribs.push("world0");
  93134. attribs.push("world1");
  93135. attribs.push("world2");
  93136. attribs.push("world3");
  93137. }
  93138. // Get correct effect
  93139. var join = defines.join("\n");
  93140. if (this._cachedDefines !== join) {
  93141. this._cachedDefines = join;
  93142. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  93143. }
  93144. return this._effect.isReady();
  93145. };
  93146. return OutlineRenderer;
  93147. }());
  93148. BABYLON.OutlineRenderer = OutlineRenderer;
  93149. })(BABYLON || (BABYLON = {}));
  93150. //# sourceMappingURL=babylon.outlineRenderer.js.map
  93151. var BABYLON;
  93152. (function (BABYLON) {
  93153. var FaceAdjacencies = /** @class */ (function () {
  93154. function FaceAdjacencies() {
  93155. this.edges = new Array();
  93156. this.edgesConnectedCount = 0;
  93157. }
  93158. return FaceAdjacencies;
  93159. }());
  93160. var EdgesRenderer = /** @class */ (function () {
  93161. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  93162. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  93163. if (epsilon === void 0) { epsilon = 0.95; }
  93164. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  93165. this.edgesWidthScalerForOrthographic = 1000.0;
  93166. this.edgesWidthScalerForPerspective = 50.0;
  93167. this._linesPositions = new Array();
  93168. this._linesNormals = new Array();
  93169. this._linesIndices = new Array();
  93170. this._buffers = {};
  93171. this._checkVerticesInsteadOfIndices = false;
  93172. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  93173. this.isEnabled = true;
  93174. this._source = source;
  93175. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  93176. this._epsilon = epsilon;
  93177. this._prepareRessources();
  93178. this._generateEdgesLines();
  93179. }
  93180. EdgesRenderer.prototype._prepareRessources = function () {
  93181. if (this._lineShader) {
  93182. return;
  93183. }
  93184. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  93185. attributes: ["position", "normal"],
  93186. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  93187. });
  93188. this._lineShader.disableDepthWrite = true;
  93189. this._lineShader.backFaceCulling = false;
  93190. };
  93191. EdgesRenderer.prototype._rebuild = function () {
  93192. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93193. if (buffer) {
  93194. buffer._rebuild();
  93195. }
  93196. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93197. if (buffer) {
  93198. buffer._rebuild();
  93199. }
  93200. var scene = this._source.getScene();
  93201. var engine = scene.getEngine();
  93202. this._ib = engine.createIndexBuffer(this._linesIndices);
  93203. };
  93204. EdgesRenderer.prototype.dispose = function () {
  93205. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  93206. if (buffer) {
  93207. buffer.dispose();
  93208. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  93209. }
  93210. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  93211. if (buffer) {
  93212. buffer.dispose();
  93213. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  93214. }
  93215. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  93216. this._lineShader.dispose();
  93217. };
  93218. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  93219. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  93220. return 0;
  93221. }
  93222. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  93223. return 1;
  93224. }
  93225. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  93226. return 2;
  93227. }
  93228. return -1;
  93229. };
  93230. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  93231. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  93232. return 0;
  93233. }
  93234. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  93235. return 1;
  93236. }
  93237. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  93238. return 2;
  93239. }
  93240. return -1;
  93241. };
  93242. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  93243. var needToCreateLine;
  93244. if (edge === undefined) {
  93245. needToCreateLine = true;
  93246. }
  93247. else {
  93248. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  93249. needToCreateLine = dotProduct < this._epsilon;
  93250. }
  93251. if (needToCreateLine) {
  93252. var offset = this._linesPositions.length / 3;
  93253. var normal = p0.subtract(p1);
  93254. normal.normalize();
  93255. // Positions
  93256. this._linesPositions.push(p0.x);
  93257. this._linesPositions.push(p0.y);
  93258. this._linesPositions.push(p0.z);
  93259. this._linesPositions.push(p0.x);
  93260. this._linesPositions.push(p0.y);
  93261. this._linesPositions.push(p0.z);
  93262. this._linesPositions.push(p1.x);
  93263. this._linesPositions.push(p1.y);
  93264. this._linesPositions.push(p1.z);
  93265. this._linesPositions.push(p1.x);
  93266. this._linesPositions.push(p1.y);
  93267. this._linesPositions.push(p1.z);
  93268. // Normals
  93269. this._linesNormals.push(p1.x);
  93270. this._linesNormals.push(p1.y);
  93271. this._linesNormals.push(p1.z);
  93272. this._linesNormals.push(-1);
  93273. this._linesNormals.push(p1.x);
  93274. this._linesNormals.push(p1.y);
  93275. this._linesNormals.push(p1.z);
  93276. this._linesNormals.push(1);
  93277. this._linesNormals.push(p0.x);
  93278. this._linesNormals.push(p0.y);
  93279. this._linesNormals.push(p0.z);
  93280. this._linesNormals.push(-1);
  93281. this._linesNormals.push(p0.x);
  93282. this._linesNormals.push(p0.y);
  93283. this._linesNormals.push(p0.z);
  93284. this._linesNormals.push(1);
  93285. // Indices
  93286. this._linesIndices.push(offset);
  93287. this._linesIndices.push(offset + 1);
  93288. this._linesIndices.push(offset + 2);
  93289. this._linesIndices.push(offset);
  93290. this._linesIndices.push(offset + 2);
  93291. this._linesIndices.push(offset + 3);
  93292. }
  93293. };
  93294. EdgesRenderer.prototype._generateEdgesLines = function () {
  93295. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93296. var indices = this._source.getIndices();
  93297. if (!indices || !positions) {
  93298. return;
  93299. }
  93300. // First let's find adjacencies
  93301. var adjacencies = new Array();
  93302. var faceNormals = new Array();
  93303. var index;
  93304. var faceAdjacencies;
  93305. // Prepare faces
  93306. for (index = 0; index < indices.length; index += 3) {
  93307. faceAdjacencies = new FaceAdjacencies();
  93308. var p0Index = indices[index];
  93309. var p1Index = indices[index + 1];
  93310. var p2Index = indices[index + 2];
  93311. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  93312. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  93313. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  93314. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  93315. faceNormal.normalize();
  93316. faceNormals.push(faceNormal);
  93317. adjacencies.push(faceAdjacencies);
  93318. }
  93319. // Scan
  93320. for (index = 0; index < adjacencies.length; index++) {
  93321. faceAdjacencies = adjacencies[index];
  93322. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  93323. var otherFaceAdjacencies = adjacencies[otherIndex];
  93324. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  93325. break;
  93326. }
  93327. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  93328. continue;
  93329. }
  93330. var otherP0 = indices[otherIndex * 3];
  93331. var otherP1 = indices[otherIndex * 3 + 1];
  93332. var otherP2 = indices[otherIndex * 3 + 2];
  93333. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  93334. var otherEdgeIndex = 0;
  93335. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  93336. continue;
  93337. }
  93338. switch (edgeIndex) {
  93339. case 0:
  93340. if (this._checkVerticesInsteadOfIndices) {
  93341. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93342. }
  93343. else {
  93344. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  93345. }
  93346. break;
  93347. case 1:
  93348. if (this._checkVerticesInsteadOfIndices) {
  93349. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93350. }
  93351. else {
  93352. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  93353. }
  93354. break;
  93355. case 2:
  93356. if (this._checkVerticesInsteadOfIndices) {
  93357. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  93358. }
  93359. else {
  93360. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  93361. }
  93362. break;
  93363. }
  93364. if (otherEdgeIndex === -1) {
  93365. continue;
  93366. }
  93367. faceAdjacencies.edges[edgeIndex] = otherIndex;
  93368. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  93369. faceAdjacencies.edgesConnectedCount++;
  93370. otherFaceAdjacencies.edgesConnectedCount++;
  93371. if (faceAdjacencies.edgesConnectedCount === 3) {
  93372. break;
  93373. }
  93374. }
  93375. }
  93376. }
  93377. // Create lines
  93378. for (index = 0; index < adjacencies.length; index++) {
  93379. // 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
  93380. var current = adjacencies[index];
  93381. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  93382. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  93383. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  93384. }
  93385. // Merge into a single mesh
  93386. var engine = this._source.getScene().getEngine();
  93387. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  93388. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  93389. this._ib = engine.createIndexBuffer(this._linesIndices);
  93390. this._indicesCount = this._linesIndices.length;
  93391. };
  93392. EdgesRenderer.prototype.render = function () {
  93393. var scene = this._source.getScene();
  93394. if (!this._lineShader.isReady() || !scene.activeCamera) {
  93395. return;
  93396. }
  93397. var engine = scene.getEngine();
  93398. this._lineShader._preBind();
  93399. // VBOs
  93400. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  93401. scene.resetCachedMaterial();
  93402. this._lineShader.setColor4("color", this._source.edgesColor);
  93403. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  93404. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  93405. }
  93406. else {
  93407. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  93408. }
  93409. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  93410. this._lineShader.bind(this._source.getWorldMatrix());
  93411. // Draw order
  93412. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  93413. this._lineShader.unbind();
  93414. engine.setDepthWrite(true);
  93415. };
  93416. return EdgesRenderer;
  93417. }());
  93418. BABYLON.EdgesRenderer = EdgesRenderer;
  93419. })(BABYLON || (BABYLON = {}));
  93420. //# sourceMappingURL=babylon.edgesRenderer.js.map
  93421. var __assign = (this && this.__assign) || Object.assign || function(t) {
  93422. for (var s, i = 1, n = arguments.length; i < n; i++) {
  93423. s = arguments[i];
  93424. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  93425. t[p] = s[p];
  93426. }
  93427. return t;
  93428. };
  93429. var BABYLON;
  93430. (function (BABYLON) {
  93431. /**
  93432. * The effect layer Helps adding post process effect blended with the main pass.
  93433. *
  93434. * This can be for instance use to generate glow or higlight effects on the scene.
  93435. *
  93436. * The effect layer class can not be used directly and is intented to inherited from to be
  93437. * customized per effects.
  93438. */
  93439. var EffectLayer = /** @class */ (function () {
  93440. /**
  93441. * Instantiates a new effect Layer and references it in the scene.
  93442. * @param name The name of the layer
  93443. * @param scene The scene to use the layer in
  93444. */
  93445. function EffectLayer(
  93446. /** The Friendly of the effect in the scene */
  93447. name, scene) {
  93448. this._vertexBuffers = {};
  93449. this._maxSize = 0;
  93450. this._mainTextureDesiredSize = { width: 0, height: 0 };
  93451. this._shouldRender = true;
  93452. this._postProcesses = [];
  93453. this._textures = [];
  93454. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  93455. /**
  93456. * The clear color of the texture used to generate the glow map.
  93457. */
  93458. this.neutralColor = new BABYLON.Color4();
  93459. /**
  93460. * Specifies wether the highlight layer is enabled or not.
  93461. */
  93462. this.isEnabled = true;
  93463. /**
  93464. * An event triggered when the effect layer has been disposed.
  93465. */
  93466. this.onDisposeObservable = new BABYLON.Observable();
  93467. /**
  93468. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  93469. */
  93470. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  93471. /**
  93472. * An event triggered when the generated texture is being merged in the scene.
  93473. */
  93474. this.onBeforeComposeObservable = new BABYLON.Observable();
  93475. /**
  93476. * An event triggered when the generated texture has been merged in the scene.
  93477. */
  93478. this.onAfterComposeObservable = new BABYLON.Observable();
  93479. /**
  93480. * An event triggered when the efffect layer changes its size.
  93481. */
  93482. this.onSizeChangedObservable = new BABYLON.Observable();
  93483. this.name = name;
  93484. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93485. this._engine = scene.getEngine();
  93486. this._maxSize = this._engine.getCaps().maxTextureSize;
  93487. this._scene.effectLayers.push(this);
  93488. // Generate Buffers
  93489. this._generateIndexBuffer();
  93490. this._genrateVertexBuffer();
  93491. }
  93492. Object.defineProperty(EffectLayer.prototype, "camera", {
  93493. /**
  93494. * Gets the camera attached to the layer.
  93495. */
  93496. get: function () {
  93497. return this._effectLayerOptions.camera;
  93498. },
  93499. enumerable: true,
  93500. configurable: true
  93501. });
  93502. /**
  93503. * Initializes the effect layer with the required options.
  93504. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  93505. */
  93506. EffectLayer.prototype._init = function (options) {
  93507. // Adapt options
  93508. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93509. this._setMainTextureSize();
  93510. this._createMainTexture();
  93511. this._createTextureAndPostProcesses();
  93512. this._mergeEffect = this._createMergeEffect();
  93513. };
  93514. /**
  93515. * Generates the index buffer of the full screen quad blending to the main canvas.
  93516. */
  93517. EffectLayer.prototype._generateIndexBuffer = function () {
  93518. // Indices
  93519. var indices = [];
  93520. indices.push(0);
  93521. indices.push(1);
  93522. indices.push(2);
  93523. indices.push(0);
  93524. indices.push(2);
  93525. indices.push(3);
  93526. this._indexBuffer = this._engine.createIndexBuffer(indices);
  93527. };
  93528. /**
  93529. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  93530. */
  93531. EffectLayer.prototype._genrateVertexBuffer = function () {
  93532. // VBO
  93533. var vertices = [];
  93534. vertices.push(1, 1);
  93535. vertices.push(-1, 1);
  93536. vertices.push(-1, -1);
  93537. vertices.push(1, -1);
  93538. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93539. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93540. };
  93541. /**
  93542. * Sets the main texture desired size which is the closest power of two
  93543. * of the engine canvas size.
  93544. */
  93545. EffectLayer.prototype._setMainTextureSize = function () {
  93546. if (this._effectLayerOptions.mainTextureFixedSize) {
  93547. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  93548. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  93549. }
  93550. else {
  93551. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  93552. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  93553. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  93554. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  93555. }
  93556. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  93557. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  93558. };
  93559. /**
  93560. * Creates the main texture for the effect layer.
  93561. */
  93562. EffectLayer.prototype._createMainTexture = function () {
  93563. var _this = this;
  93564. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  93565. width: this._mainTextureDesiredSize.width,
  93566. height: this._mainTextureDesiredSize.height
  93567. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93568. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  93569. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93570. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93571. this._mainTexture.anisotropicFilteringLevel = 1;
  93572. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93573. this._mainTexture.renderParticles = false;
  93574. this._mainTexture.renderList = null;
  93575. this._mainTexture.ignoreCameraViewport = true;
  93576. // Custom render function
  93577. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  93578. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  93579. var index;
  93580. var engine = _this._scene.getEngine();
  93581. if (depthOnlySubMeshes.length) {
  93582. engine.setColorWrite(false);
  93583. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  93584. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  93585. }
  93586. engine.setColorWrite(true);
  93587. }
  93588. for (index = 0; index < opaqueSubMeshes.length; index++) {
  93589. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  93590. }
  93591. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  93592. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  93593. }
  93594. for (index = 0; index < transparentSubMeshes.length; index++) {
  93595. _this._renderSubMesh(transparentSubMeshes.data[index]);
  93596. }
  93597. };
  93598. this._mainTexture.onClearObservable.add(function (engine) {
  93599. engine.clear(_this.neutralColor, true, true, true);
  93600. });
  93601. };
  93602. /**
  93603. * Checks for the readiness of the element composing the layer.
  93604. * @param subMesh the mesh to check for
  93605. * @param useInstances specify wether or not to use instances to render the mesh
  93606. * @param emissiveTexture the associated emissive texture used to generate the glow
  93607. * @return true if ready otherwise, false
  93608. */
  93609. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  93610. var material = subMesh.getMaterial();
  93611. if (!material) {
  93612. return false;
  93613. }
  93614. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  93615. return false;
  93616. }
  93617. var defines = [];
  93618. var attribs = [BABYLON.VertexBuffer.PositionKind];
  93619. var mesh = subMesh.getMesh();
  93620. var uv1 = false;
  93621. var uv2 = false;
  93622. // Alpha test
  93623. if (material && material.needAlphaTesting()) {
  93624. var alphaTexture = material.getAlphaTestTexture();
  93625. if (alphaTexture) {
  93626. defines.push("#define ALPHATEST");
  93627. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93628. alphaTexture.coordinatesIndex === 1) {
  93629. defines.push("#define DIFFUSEUV2");
  93630. uv2 = true;
  93631. }
  93632. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93633. defines.push("#define DIFFUSEUV1");
  93634. uv1 = true;
  93635. }
  93636. }
  93637. }
  93638. // Emissive
  93639. if (emissiveTexture) {
  93640. defines.push("#define EMISSIVE");
  93641. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  93642. emissiveTexture.coordinatesIndex === 1) {
  93643. defines.push("#define EMISSIVEUV2");
  93644. uv2 = true;
  93645. }
  93646. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93647. defines.push("#define EMISSIVEUV1");
  93648. uv1 = true;
  93649. }
  93650. }
  93651. if (uv1) {
  93652. attribs.push(BABYLON.VertexBuffer.UVKind);
  93653. defines.push("#define UV1");
  93654. }
  93655. if (uv2) {
  93656. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93657. defines.push("#define UV2");
  93658. }
  93659. // Bones
  93660. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93661. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93662. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93663. if (mesh.numBoneInfluencers > 4) {
  93664. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93665. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93666. }
  93667. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93668. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  93669. }
  93670. else {
  93671. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93672. }
  93673. // Morph targets
  93674. var manager = mesh.morphTargetManager;
  93675. var morphInfluencers = 0;
  93676. if (manager) {
  93677. if (manager.numInfluencers > 0) {
  93678. defines.push("#define MORPHTARGETS");
  93679. morphInfluencers = manager.numInfluencers;
  93680. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  93681. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  93682. }
  93683. }
  93684. // Instances
  93685. if (useInstances) {
  93686. defines.push("#define INSTANCES");
  93687. attribs.push("world0");
  93688. attribs.push("world1");
  93689. attribs.push("world2");
  93690. attribs.push("world3");
  93691. }
  93692. // Get correct effect
  93693. var join = defines.join("\n");
  93694. if (this._cachedDefines !== join) {
  93695. this._cachedDefines = join;
  93696. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  93697. }
  93698. return this._effectLayerMapGenerationEffect.isReady();
  93699. };
  93700. /**
  93701. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  93702. */
  93703. EffectLayer.prototype.render = function () {
  93704. var currentEffect = this._mergeEffect;
  93705. // Check
  93706. if (!currentEffect.isReady())
  93707. return;
  93708. for (var i = 0; i < this._postProcesses.length; i++) {
  93709. if (!this._postProcesses[i].isReady()) {
  93710. return;
  93711. }
  93712. }
  93713. var engine = this._scene.getEngine();
  93714. this.onBeforeComposeObservable.notifyObservers(this);
  93715. // Render
  93716. engine.enableEffect(currentEffect);
  93717. engine.setState(false);
  93718. // VBOs
  93719. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93720. // Cache
  93721. var previousAlphaMode = engine.getAlphaMode();
  93722. // Go Blend.
  93723. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  93724. // Blends the map on the main canvas.
  93725. this._internalRender(currentEffect);
  93726. // Restore Alpha
  93727. engine.setAlphaMode(previousAlphaMode);
  93728. this.onAfterComposeObservable.notifyObservers(this);
  93729. // Handle size changes.
  93730. var size = this._mainTexture.getSize();
  93731. this._setMainTextureSize();
  93732. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  93733. // Recreate RTT and post processes on size change.
  93734. this.onSizeChangedObservable.notifyObservers(this);
  93735. this._disposeTextureAndPostProcesses();
  93736. this._createMainTexture();
  93737. this._createTextureAndPostProcesses();
  93738. }
  93739. };
  93740. /**
  93741. * Determine if a given mesh will be used in the current effect.
  93742. * @param mesh mesh to test
  93743. * @returns true if the mesh will be used
  93744. */
  93745. EffectLayer.prototype.hasMesh = function (mesh) {
  93746. return true;
  93747. };
  93748. /**
  93749. * Returns true if the layer contains information to display, otherwise false.
  93750. * @returns true if the glow layer should be rendered
  93751. */
  93752. EffectLayer.prototype.shouldRender = function () {
  93753. return this.isEnabled && this._shouldRender;
  93754. };
  93755. /**
  93756. * Returns true if the mesh should render, otherwise false.
  93757. * @param mesh The mesh to render
  93758. * @returns true if it should render otherwise false
  93759. */
  93760. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  93761. return true;
  93762. };
  93763. /**
  93764. * Returns true if the mesh should render, otherwise false.
  93765. * @param mesh The mesh to render
  93766. * @returns true if it should render otherwise false
  93767. */
  93768. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  93769. return true;
  93770. };
  93771. /**
  93772. * Renders the submesh passed in parameter to the generation map.
  93773. */
  93774. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  93775. var _this = this;
  93776. if (!this.shouldRender()) {
  93777. return;
  93778. }
  93779. var material = subMesh.getMaterial();
  93780. var mesh = subMesh.getRenderingMesh();
  93781. var scene = this._scene;
  93782. var engine = scene.getEngine();
  93783. if (!material) {
  93784. return;
  93785. }
  93786. // Do not block in blend mode.
  93787. if (material.needAlphaBlendingForMesh(mesh)) {
  93788. return;
  93789. }
  93790. // Culling
  93791. engine.setState(material.backFaceCulling);
  93792. // Managing instances
  93793. var batch = mesh._getInstancesRenderList(subMesh._id);
  93794. if (batch.mustReturn) {
  93795. return;
  93796. }
  93797. // Early Exit per mesh
  93798. if (!this._shouldRenderMesh(mesh)) {
  93799. return;
  93800. }
  93801. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93802. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  93803. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  93804. engine.enableEffect(this._effectLayerMapGenerationEffect);
  93805. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  93806. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  93807. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  93808. // Alpha test
  93809. if (material && material.needAlphaTesting()) {
  93810. var alphaTexture = material.getAlphaTestTexture();
  93811. if (alphaTexture) {
  93812. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  93813. var textureMatrix = alphaTexture.getTextureMatrix();
  93814. if (textureMatrix) {
  93815. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  93816. }
  93817. }
  93818. }
  93819. // Glow emissive only
  93820. if (this._emissiveTextureAndColor.texture) {
  93821. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  93822. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  93823. }
  93824. // Bones
  93825. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93826. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93827. }
  93828. // Morph targets
  93829. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  93830. // Draw
  93831. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  93832. }
  93833. else {
  93834. // Need to reset refresh rate of the shadowMap
  93835. this._mainTexture.resetRefreshCounter();
  93836. }
  93837. };
  93838. /**
  93839. * Rebuild the required buffers.
  93840. * @hidden Internal use only.
  93841. */
  93842. EffectLayer.prototype._rebuild = function () {
  93843. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93844. if (vb) {
  93845. vb._rebuild();
  93846. }
  93847. this._generateIndexBuffer();
  93848. };
  93849. /**
  93850. * Dispose only the render target textures and post process.
  93851. */
  93852. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  93853. this._mainTexture.dispose();
  93854. for (var i = 0; i < this._postProcesses.length; i++) {
  93855. if (this._postProcesses[i]) {
  93856. this._postProcesses[i].dispose();
  93857. }
  93858. }
  93859. this._postProcesses = [];
  93860. for (var i = 0; i < this._textures.length; i++) {
  93861. if (this._textures[i]) {
  93862. this._textures[i].dispose();
  93863. }
  93864. }
  93865. this._textures = [];
  93866. };
  93867. /**
  93868. * Dispose the highlight layer and free resources.
  93869. */
  93870. EffectLayer.prototype.dispose = function () {
  93871. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93872. if (vertexBuffer) {
  93873. vertexBuffer.dispose();
  93874. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93875. }
  93876. if (this._indexBuffer) {
  93877. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93878. this._indexBuffer = null;
  93879. }
  93880. // Clean textures and post processes
  93881. this._disposeTextureAndPostProcesses();
  93882. // Remove from scene
  93883. var index = this._scene.effectLayers.indexOf(this, 0);
  93884. if (index > -1) {
  93885. this._scene.effectLayers.splice(index, 1);
  93886. }
  93887. // Callback
  93888. this.onDisposeObservable.notifyObservers(this);
  93889. this.onDisposeObservable.clear();
  93890. this.onBeforeRenderMainTextureObservable.clear();
  93891. this.onBeforeComposeObservable.clear();
  93892. this.onAfterComposeObservable.clear();
  93893. this.onSizeChangedObservable.clear();
  93894. };
  93895. /**
  93896. * Gets the class name of the effect layer
  93897. * @returns the string with the class name of the effect layer
  93898. */
  93899. EffectLayer.prototype.getClassName = function () {
  93900. return "EffectLayer";
  93901. };
  93902. /**
  93903. * Creates an effect layer from parsed effect layer data
  93904. * @param parsedEffectLayer defines effect layer data
  93905. * @param scene defines the current scene
  93906. * @param rootUrl defines the root URL containing the effect layer information
  93907. * @returns a parsed effect Layer
  93908. */
  93909. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  93910. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  93911. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  93912. };
  93913. __decorate([
  93914. BABYLON.serialize()
  93915. ], EffectLayer.prototype, "name", void 0);
  93916. __decorate([
  93917. BABYLON.serializeAsColor4()
  93918. ], EffectLayer.prototype, "neutralColor", void 0);
  93919. __decorate([
  93920. BABYLON.serialize()
  93921. ], EffectLayer.prototype, "isEnabled", void 0);
  93922. __decorate([
  93923. BABYLON.serializeAsCameraReference()
  93924. ], EffectLayer.prototype, "camera", null);
  93925. return EffectLayer;
  93926. }());
  93927. BABYLON.EffectLayer = EffectLayer;
  93928. })(BABYLON || (BABYLON = {}));
  93929. //# sourceMappingURL=babylon.effectLayer.js.map
  93930. var BABYLON;
  93931. (function (BABYLON) {
  93932. /**
  93933. * Special Glow Blur post process only blurring the alpha channel
  93934. * It enforces keeping the most luminous color in the color channel.
  93935. */
  93936. var GlowBlurPostProcess = /** @class */ (function (_super) {
  93937. __extends(GlowBlurPostProcess, _super);
  93938. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  93939. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  93940. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  93941. _this.direction = direction;
  93942. _this.kernel = kernel;
  93943. _this.onApplyObservable.add(function (effect) {
  93944. effect.setFloat2("screenSize", _this.width, _this.height);
  93945. effect.setVector2("direction", _this.direction);
  93946. effect.setFloat("blurWidth", _this.kernel);
  93947. });
  93948. return _this;
  93949. }
  93950. return GlowBlurPostProcess;
  93951. }(BABYLON.PostProcess));
  93952. /**
  93953. * The highlight layer Helps adding a glow effect around a mesh.
  93954. *
  93955. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93956. * glowy meshes to your scene.
  93957. *
  93958. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  93959. */
  93960. var HighlightLayer = /** @class */ (function (_super) {
  93961. __extends(HighlightLayer, _super);
  93962. /**
  93963. * Instantiates a new highlight Layer and references it to the scene..
  93964. * @param name The name of the layer
  93965. * @param scene The scene to use the layer in
  93966. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  93967. */
  93968. function HighlightLayer(name, scene, options) {
  93969. var _this = _super.call(this, name, scene) || this;
  93970. _this.name = name;
  93971. /**
  93972. * Specifies whether or not the inner glow is ACTIVE in the layer.
  93973. */
  93974. _this.innerGlow = true;
  93975. /**
  93976. * Specifies whether or not the outer glow is ACTIVE in the layer.
  93977. */
  93978. _this.outerGlow = true;
  93979. /**
  93980. * An event triggered when the highlight layer is being blurred.
  93981. */
  93982. _this.onBeforeBlurObservable = new BABYLON.Observable();
  93983. /**
  93984. * An event triggered when the highlight layer has been blurred.
  93985. */
  93986. _this.onAfterBlurObservable = new BABYLON.Observable();
  93987. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  93988. _this._meshes = {};
  93989. _this._excludedMeshes = {};
  93990. _this.neutralColor = HighlightLayer.NeutralColor;
  93991. // Warn on stencil
  93992. if (!_this._engine.isStencilEnable) {
  93993. 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 }");
  93994. }
  93995. // Adapt options
  93996. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93997. // Initialize the layer
  93998. _this._init({
  93999. alphaBlendingMode: _this._options.alphaBlendingMode,
  94000. camera: _this._options.camera,
  94001. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94002. mainTextureRatio: _this._options.mainTextureRatio
  94003. });
  94004. // Do not render as long as no meshes have been added
  94005. _this._shouldRender = false;
  94006. return _this;
  94007. }
  94008. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  94009. /**
  94010. * Gets the horizontal size of the blur.
  94011. */
  94012. get: function () {
  94013. return this._horizontalBlurPostprocess.kernel;
  94014. },
  94015. /**
  94016. * Specifies the horizontal size of the blur.
  94017. */
  94018. set: function (value) {
  94019. this._horizontalBlurPostprocess.kernel = value;
  94020. },
  94021. enumerable: true,
  94022. configurable: true
  94023. });
  94024. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  94025. /**
  94026. * Gets the vertical size of the blur.
  94027. */
  94028. get: function () {
  94029. return this._verticalBlurPostprocess.kernel;
  94030. },
  94031. /**
  94032. * Specifies the vertical size of the blur.
  94033. */
  94034. set: function (value) {
  94035. this._verticalBlurPostprocess.kernel = value;
  94036. },
  94037. enumerable: true,
  94038. configurable: true
  94039. });
  94040. /**
  94041. * Get the effect name of the layer.
  94042. * @return The effect name
  94043. */
  94044. HighlightLayer.prototype.getEffectName = function () {
  94045. return HighlightLayer.EffectName;
  94046. };
  94047. /**
  94048. * Create the merge effect. This is the shader use to blit the information back
  94049. * to the main canvas at the end of the scene rendering.
  94050. */
  94051. HighlightLayer.prototype._createMergeEffect = function () {
  94052. // Effect
  94053. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  94054. };
  94055. /**
  94056. * Creates the render target textures and post processes used in the highlight layer.
  94057. */
  94058. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  94059. var _this = this;
  94060. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  94061. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  94062. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94063. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94064. var textureType = 0;
  94065. if (this._engine.getCaps().textureHalfFloatRender) {
  94066. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94067. }
  94068. else {
  94069. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94070. }
  94071. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  94072. width: blurTextureWidth,
  94073. height: blurTextureHeight
  94074. }, this._scene, false, true, textureType);
  94075. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94076. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94077. this._blurTexture.anisotropicFilteringLevel = 16;
  94078. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  94079. this._blurTexture.renderParticles = false;
  94080. this._blurTexture.ignoreCameraViewport = true;
  94081. this._textures = [this._blurTexture];
  94082. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  94083. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94084. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  94085. effect.setTexture("textureSampler", _this._mainTexture);
  94086. });
  94087. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94088. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94089. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94090. });
  94091. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  94092. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  94093. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  94094. });
  94095. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94096. }
  94097. else {
  94098. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  94099. width: blurTextureWidth,
  94100. height: blurTextureHeight
  94101. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94102. this._horizontalBlurPostprocess.width = blurTextureWidth;
  94103. this._horizontalBlurPostprocess.height = blurTextureHeight;
  94104. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  94105. effect.setTexture("textureSampler", _this._mainTexture);
  94106. });
  94107. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  94108. width: blurTextureWidth,
  94109. height: blurTextureHeight
  94110. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94111. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  94112. }
  94113. this._mainTexture.onAfterUnbindObservable.add(function () {
  94114. _this.onBeforeBlurObservable.notifyObservers(_this);
  94115. var internalTexture = _this._blurTexture.getInternalTexture();
  94116. if (internalTexture) {
  94117. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  94118. }
  94119. _this.onAfterBlurObservable.notifyObservers(_this);
  94120. });
  94121. // Prevent autoClear.
  94122. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94123. };
  94124. /**
  94125. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94126. */
  94127. HighlightLayer.prototype.needStencil = function () {
  94128. return true;
  94129. };
  94130. /**
  94131. * Checks for the readiness of the element composing the layer.
  94132. * @param subMesh the mesh to check for
  94133. * @param useInstances specify wether or not to use instances to render the mesh
  94134. * @param emissiveTexture the associated emissive texture used to generate the glow
  94135. * @return true if ready otherwise, false
  94136. */
  94137. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  94138. var material = subMesh.getMaterial();
  94139. var mesh = subMesh.getRenderingMesh();
  94140. if (!material || !mesh || !this._meshes) {
  94141. return false;
  94142. }
  94143. var emissiveTexture = null;
  94144. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94145. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94146. emissiveTexture = material.emissiveTexture;
  94147. }
  94148. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94149. };
  94150. /**
  94151. * Implementation specific of rendering the generating effect on the main canvas.
  94152. * @param effect The effect used to render through
  94153. */
  94154. HighlightLayer.prototype._internalRender = function (effect) {
  94155. // Texture
  94156. effect.setTexture("textureSampler", this._blurTexture);
  94157. // Cache
  94158. var engine = this._engine;
  94159. var previousStencilBuffer = engine.getStencilBuffer();
  94160. var previousStencilFunction = engine.getStencilFunction();
  94161. var previousStencilMask = engine.getStencilMask();
  94162. var previousStencilOperationPass = engine.getStencilOperationPass();
  94163. var previousStencilOperationFail = engine.getStencilOperationFail();
  94164. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  94165. var previousStencilReference = engine.getStencilFunctionReference();
  94166. // Stencil operations
  94167. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  94168. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  94169. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  94170. // Draw order
  94171. engine.setStencilMask(0x00);
  94172. engine.setStencilBuffer(true);
  94173. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  94174. // 2 passes inner outer
  94175. if (this.outerGlow) {
  94176. effect.setFloat("offset", 0);
  94177. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  94178. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94179. }
  94180. if (this.innerGlow) {
  94181. effect.setFloat("offset", 1);
  94182. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  94183. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94184. }
  94185. // Restore Cache
  94186. engine.setStencilFunction(previousStencilFunction);
  94187. engine.setStencilMask(previousStencilMask);
  94188. engine.setStencilBuffer(previousStencilBuffer);
  94189. engine.setStencilOperationPass(previousStencilOperationPass);
  94190. engine.setStencilOperationFail(previousStencilOperationFail);
  94191. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  94192. engine.setStencilFunctionReference(previousStencilReference);
  94193. };
  94194. /**
  94195. * Returns true if the layer contains information to display, otherwise false.
  94196. */
  94197. HighlightLayer.prototype.shouldRender = function () {
  94198. if (_super.prototype.shouldRender.call(this)) {
  94199. return this._meshes ? true : false;
  94200. }
  94201. return false;
  94202. };
  94203. /**
  94204. * Returns true if the mesh should render, otherwise false.
  94205. * @param mesh The mesh to render
  94206. * @returns true if it should render otherwise false
  94207. */
  94208. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  94209. // Excluded Mesh
  94210. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  94211. return false;
  94212. }
  94213. ;
  94214. return true;
  94215. };
  94216. /**
  94217. * Sets the required values for both the emissive texture and and the main color.
  94218. */
  94219. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94220. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  94221. if (highlightLayerMesh) {
  94222. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  94223. }
  94224. else {
  94225. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94226. }
  94227. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  94228. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94229. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  94230. }
  94231. else {
  94232. this._emissiveTextureAndColor.texture = null;
  94233. }
  94234. };
  94235. /**
  94236. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  94237. * @param mesh The mesh to exclude from the highlight layer
  94238. */
  94239. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  94240. if (!this._excludedMeshes) {
  94241. return;
  94242. }
  94243. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94244. if (!meshExcluded) {
  94245. this._excludedMeshes[mesh.uniqueId] = {
  94246. mesh: mesh,
  94247. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  94248. mesh.getEngine().setStencilBuffer(false);
  94249. }),
  94250. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  94251. mesh.getEngine().setStencilBuffer(true);
  94252. }),
  94253. };
  94254. }
  94255. };
  94256. /**
  94257. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  94258. * @param mesh The mesh to highlight
  94259. */
  94260. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  94261. if (!this._excludedMeshes) {
  94262. return;
  94263. }
  94264. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  94265. if (meshExcluded) {
  94266. if (meshExcluded.beforeRender) {
  94267. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  94268. }
  94269. if (meshExcluded.afterRender) {
  94270. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  94271. }
  94272. }
  94273. this._excludedMeshes[mesh.uniqueId] = null;
  94274. };
  94275. /**
  94276. * Determine if a given mesh will be highlighted by the current HighlightLayer
  94277. * @param mesh mesh to test
  94278. * @returns true if the mesh will be highlighted by the current HighlightLayer
  94279. */
  94280. HighlightLayer.prototype.hasMesh = function (mesh) {
  94281. if (!this._meshes) {
  94282. return false;
  94283. }
  94284. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  94285. };
  94286. /**
  94287. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  94288. * @param mesh The mesh to highlight
  94289. * @param color The color of the highlight
  94290. * @param glowEmissiveOnly Extract the glow from the emissive texture
  94291. */
  94292. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  94293. var _this = this;
  94294. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  94295. if (!this._meshes) {
  94296. return;
  94297. }
  94298. var meshHighlight = this._meshes[mesh.uniqueId];
  94299. if (meshHighlight) {
  94300. meshHighlight.color = color;
  94301. }
  94302. else {
  94303. this._meshes[mesh.uniqueId] = {
  94304. mesh: mesh,
  94305. color: color,
  94306. // Lambda required for capture due to Observable this context
  94307. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  94308. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  94309. _this._defaultStencilReference(mesh);
  94310. }
  94311. else {
  94312. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  94313. }
  94314. }),
  94315. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  94316. glowEmissiveOnly: glowEmissiveOnly
  94317. };
  94318. }
  94319. this._shouldRender = true;
  94320. };
  94321. /**
  94322. * Remove a mesh from the highlight layer in order to make it stop glowing.
  94323. * @param mesh The mesh to highlight
  94324. */
  94325. HighlightLayer.prototype.removeMesh = function (mesh) {
  94326. if (!this._meshes) {
  94327. return;
  94328. }
  94329. var meshHighlight = this._meshes[mesh.uniqueId];
  94330. if (meshHighlight) {
  94331. if (meshHighlight.observerHighlight) {
  94332. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94333. }
  94334. if (meshHighlight.observerDefault) {
  94335. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94336. }
  94337. delete this._meshes[mesh.uniqueId];
  94338. }
  94339. this._shouldRender = false;
  94340. for (var meshHighlightToCheck in this._meshes) {
  94341. if (this._meshes[meshHighlightToCheck]) {
  94342. this._shouldRender = true;
  94343. break;
  94344. }
  94345. }
  94346. };
  94347. /**
  94348. * Force the stencil to the normal expected value for none glowing parts
  94349. */
  94350. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  94351. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  94352. };
  94353. /**
  94354. * Free any resources and references associated to a mesh.
  94355. * Internal use
  94356. * @param mesh The mesh to free.
  94357. */
  94358. HighlightLayer.prototype._disposeMesh = function (mesh) {
  94359. this.removeMesh(mesh);
  94360. this.removeExcludedMesh(mesh);
  94361. };
  94362. /**
  94363. * Dispose the highlight layer and free resources.
  94364. */
  94365. HighlightLayer.prototype.dispose = function () {
  94366. if (this._meshes) {
  94367. // Clean mesh references
  94368. for (var id in this._meshes) {
  94369. var meshHighlight = this._meshes[id];
  94370. if (meshHighlight && meshHighlight.mesh) {
  94371. if (meshHighlight.observerHighlight) {
  94372. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  94373. }
  94374. if (meshHighlight.observerDefault) {
  94375. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  94376. }
  94377. }
  94378. }
  94379. this._meshes = null;
  94380. }
  94381. if (this._excludedMeshes) {
  94382. for (var id in this._excludedMeshes) {
  94383. var meshHighlight = this._excludedMeshes[id];
  94384. if (meshHighlight) {
  94385. if (meshHighlight.beforeRender) {
  94386. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  94387. }
  94388. if (meshHighlight.afterRender) {
  94389. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  94390. }
  94391. }
  94392. }
  94393. this._excludedMeshes = null;
  94394. }
  94395. _super.prototype.dispose.call(this);
  94396. };
  94397. /**
  94398. * Gets the class name of the effect layer
  94399. * @returns the string with the class name of the effect layer
  94400. */
  94401. HighlightLayer.prototype.getClassName = function () {
  94402. return "HighlightLayer";
  94403. };
  94404. /**
  94405. * Serializes this Highlight layer
  94406. * @returns a serialized Highlight layer object
  94407. */
  94408. HighlightLayer.prototype.serialize = function () {
  94409. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94410. serializationObject.customType = "BABYLON.HighlightLayer";
  94411. // Highlighted meshes
  94412. serializationObject.meshes = [];
  94413. if (this._meshes) {
  94414. for (var m in this._meshes) {
  94415. var mesh = this._meshes[m];
  94416. if (mesh) {
  94417. serializationObject.meshes.push({
  94418. glowEmissiveOnly: mesh.glowEmissiveOnly,
  94419. color: mesh.color.asArray(),
  94420. meshId: mesh.mesh.id
  94421. });
  94422. }
  94423. }
  94424. }
  94425. // Excluded meshes
  94426. serializationObject.excludedMeshes = [];
  94427. if (this._excludedMeshes) {
  94428. for (var e in this._excludedMeshes) {
  94429. var excludedMesh = this._excludedMeshes[e];
  94430. if (excludedMesh) {
  94431. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  94432. }
  94433. }
  94434. }
  94435. return serializationObject;
  94436. };
  94437. /**
  94438. * Creates a Highlight layer from parsed Highlight layer data
  94439. * @param parsedHightlightLayer defines the Highlight layer data
  94440. * @param scene defines the current scene
  94441. * @param rootUrl defines the root URL containing the Highlight layer information
  94442. * @returns a parsed Highlight layer
  94443. */
  94444. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  94445. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  94446. var index;
  94447. // Excluded meshes
  94448. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  94449. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  94450. if (mesh) {
  94451. hl.addExcludedMesh(mesh);
  94452. }
  94453. }
  94454. // Included meshes
  94455. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  94456. var highlightedMesh = parsedHightlightLayer.meshes[index];
  94457. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  94458. if (mesh) {
  94459. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  94460. }
  94461. }
  94462. return hl;
  94463. };
  94464. /**
  94465. * Effect Name of the highlight layer.
  94466. */
  94467. HighlightLayer.EffectName = "HighlightLayer";
  94468. /**
  94469. * The neutral color used during the preparation of the glow effect.
  94470. * This is black by default as the blend operation is a blend operation.
  94471. */
  94472. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  94473. /**
  94474. * Stencil value used for glowing meshes.
  94475. */
  94476. HighlightLayer.GlowingMeshStencilReference = 0x02;
  94477. /**
  94478. * Stencil value used for the other meshes in the scene.
  94479. */
  94480. HighlightLayer.NormalMeshStencilReference = 0x01;
  94481. __decorate([
  94482. BABYLON.serialize()
  94483. ], HighlightLayer.prototype, "innerGlow", void 0);
  94484. __decorate([
  94485. BABYLON.serialize()
  94486. ], HighlightLayer.prototype, "outerGlow", void 0);
  94487. __decorate([
  94488. BABYLON.serialize()
  94489. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  94490. __decorate([
  94491. BABYLON.serialize()
  94492. ], HighlightLayer.prototype, "blurVerticalSize", null);
  94493. __decorate([
  94494. BABYLON.serialize("options")
  94495. ], HighlightLayer.prototype, "_options", void 0);
  94496. return HighlightLayer;
  94497. }(BABYLON.EffectLayer));
  94498. BABYLON.HighlightLayer = HighlightLayer;
  94499. })(BABYLON || (BABYLON = {}));
  94500. //# sourceMappingURL=babylon.highlightLayer.js.map
  94501. var BABYLON;
  94502. (function (BABYLON) {
  94503. /**
  94504. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  94505. *
  94506. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  94507. * glowy meshes to your scene.
  94508. *
  94509. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  94510. */
  94511. var GlowLayer = /** @class */ (function (_super) {
  94512. __extends(GlowLayer, _super);
  94513. /**
  94514. * Instantiates a new glow Layer and references it to the scene.
  94515. * @param name The name of the layer
  94516. * @param scene The scene to use the layer in
  94517. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  94518. */
  94519. function GlowLayer(name, scene, options) {
  94520. var _this = _super.call(this, name, scene) || this;
  94521. _this._intensity = 1.0;
  94522. _this._includedOnlyMeshes = [];
  94523. _this._excludedMeshes = [];
  94524. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  94525. // Adapt options
  94526. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  94527. // Initialize the layer
  94528. _this._init({
  94529. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  94530. camera: _this._options.camera,
  94531. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  94532. mainTextureRatio: _this._options.mainTextureRatio
  94533. });
  94534. return _this;
  94535. }
  94536. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  94537. /**
  94538. * Gets the kernel size of the blur.
  94539. */
  94540. get: function () {
  94541. return this._horizontalBlurPostprocess1.kernel;
  94542. },
  94543. /**
  94544. * Sets the kernel size of the blur.
  94545. */
  94546. set: function (value) {
  94547. this._horizontalBlurPostprocess1.kernel = value;
  94548. this._verticalBlurPostprocess1.kernel = value;
  94549. this._horizontalBlurPostprocess2.kernel = value;
  94550. this._verticalBlurPostprocess2.kernel = value;
  94551. },
  94552. enumerable: true,
  94553. configurable: true
  94554. });
  94555. Object.defineProperty(GlowLayer.prototype, "intensity", {
  94556. /**
  94557. * Gets the glow intensity.
  94558. */
  94559. get: function () {
  94560. return this._intensity;
  94561. },
  94562. /**
  94563. * Sets the glow intensity.
  94564. */
  94565. set: function (value) {
  94566. this._intensity = value;
  94567. },
  94568. enumerable: true,
  94569. configurable: true
  94570. });
  94571. /**
  94572. * Get the effect name of the layer.
  94573. * @return The effect name
  94574. */
  94575. GlowLayer.prototype.getEffectName = function () {
  94576. return GlowLayer.EffectName;
  94577. };
  94578. /**
  94579. * Create the merge effect. This is the shader use to blit the information back
  94580. * to the main canvas at the end of the scene rendering.
  94581. */
  94582. GlowLayer.prototype._createMergeEffect = function () {
  94583. // Effect
  94584. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  94585. };
  94586. /**
  94587. * Creates the render target textures and post processes used in the glow layer.
  94588. */
  94589. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  94590. var _this = this;
  94591. var blurTextureWidth = this._mainTextureDesiredSize.width;
  94592. var blurTextureHeight = this._mainTextureDesiredSize.height;
  94593. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  94594. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  94595. var textureType = 0;
  94596. if (this._engine.getCaps().textureHalfFloatRender) {
  94597. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94598. }
  94599. else {
  94600. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94601. }
  94602. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  94603. width: blurTextureWidth,
  94604. height: blurTextureHeight
  94605. }, this._scene, false, true, textureType);
  94606. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94607. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94608. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94609. this._blurTexture1.renderParticles = false;
  94610. this._blurTexture1.ignoreCameraViewport = true;
  94611. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  94612. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  94613. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  94614. width: blurTextureWidth2,
  94615. height: blurTextureHeight2
  94616. }, this._scene, false, true, textureType);
  94617. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94618. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94619. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94620. this._blurTexture2.renderParticles = false;
  94621. this._blurTexture2.ignoreCameraViewport = true;
  94622. this._textures = [this._blurTexture1, this._blurTexture2];
  94623. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94624. width: blurTextureWidth,
  94625. height: blurTextureHeight
  94626. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94627. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  94628. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  94629. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  94630. effect.setTexture("textureSampler", _this._mainTexture);
  94631. });
  94632. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94633. width: blurTextureWidth,
  94634. height: blurTextureHeight
  94635. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94636. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  94637. width: blurTextureWidth2,
  94638. height: blurTextureHeight2
  94639. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94640. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  94641. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  94642. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  94643. effect.setTexture("textureSampler", _this._blurTexture1);
  94644. });
  94645. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94646. width: blurTextureWidth2,
  94647. height: blurTextureHeight2
  94648. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94649. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94650. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  94651. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94652. this._mainTexture.samples = this._options.mainTextureSamples;
  94653. this._mainTexture.onAfterUnbindObservable.add(function () {
  94654. var internalTexture = _this._blurTexture1.getInternalTexture();
  94655. if (internalTexture) {
  94656. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  94657. internalTexture = _this._blurTexture2.getInternalTexture();
  94658. if (internalTexture) {
  94659. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  94660. }
  94661. }
  94662. });
  94663. // Prevent autoClear.
  94664. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94665. };
  94666. /**
  94667. * Checks for the readiness of the element composing the layer.
  94668. * @param subMesh the mesh to check for
  94669. * @param useInstances specify wether or not to use instances to render the mesh
  94670. * @param emissiveTexture the associated emissive texture used to generate the glow
  94671. * @return true if ready otherwise, false
  94672. */
  94673. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  94674. var material = subMesh.getMaterial();
  94675. var mesh = subMesh.getRenderingMesh();
  94676. if (!material || !mesh) {
  94677. return false;
  94678. }
  94679. var emissiveTexture = material.emissiveTexture;
  94680. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94681. };
  94682. /**
  94683. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94684. */
  94685. GlowLayer.prototype.needStencil = function () {
  94686. return false;
  94687. };
  94688. /**
  94689. * Implementation specific of rendering the generating effect on the main canvas.
  94690. * @param effect The effect used to render through
  94691. */
  94692. GlowLayer.prototype._internalRender = function (effect) {
  94693. // Texture
  94694. effect.setTexture("textureSampler", this._blurTexture1);
  94695. effect.setTexture("textureSampler2", this._blurTexture2);
  94696. effect.setFloat("offset", this._intensity);
  94697. // Cache
  94698. var engine = this._engine;
  94699. var previousStencilBuffer = engine.getStencilBuffer();
  94700. // Draw order
  94701. engine.setStencilBuffer(false);
  94702. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94703. // Draw order
  94704. engine.setStencilBuffer(previousStencilBuffer);
  94705. };
  94706. /**
  94707. * Sets the required values for both the emissive texture and and the main color.
  94708. */
  94709. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94710. var textureLevel = 1.0;
  94711. if (this.customEmissiveTextureSelector) {
  94712. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  94713. }
  94714. else {
  94715. if (material) {
  94716. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94717. if (this._emissiveTextureAndColor.texture) {
  94718. textureLevel = this._emissiveTextureAndColor.texture.level;
  94719. }
  94720. }
  94721. else {
  94722. this._emissiveTextureAndColor.texture = null;
  94723. }
  94724. }
  94725. if (this.customEmissiveColorSelector) {
  94726. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  94727. }
  94728. else {
  94729. if (material.emissiveColor) {
  94730. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  94731. }
  94732. else {
  94733. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94734. }
  94735. }
  94736. };
  94737. /**
  94738. * Returns true if the mesh should render, otherwise false.
  94739. * @param mesh The mesh to render
  94740. * @returns true if it should render otherwise false
  94741. */
  94742. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  94743. return this.hasMesh(mesh);
  94744. };
  94745. /**
  94746. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  94747. * @param mesh The mesh to exclude from the glow layer
  94748. */
  94749. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  94750. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  94751. this._excludedMeshes.push(mesh.uniqueId);
  94752. }
  94753. };
  94754. /**
  94755. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  94756. * @param mesh The mesh to remove
  94757. */
  94758. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  94759. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  94760. if (index !== -1) {
  94761. this._excludedMeshes.splice(index, 1);
  94762. }
  94763. };
  94764. /**
  94765. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  94766. * @param mesh The mesh to include in the glow layer
  94767. */
  94768. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  94769. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  94770. this._includedOnlyMeshes.push(mesh.uniqueId);
  94771. }
  94772. };
  94773. /**
  94774. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  94775. * @param mesh The mesh to remove
  94776. */
  94777. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  94778. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  94779. if (index !== -1) {
  94780. this._includedOnlyMeshes.splice(index, 1);
  94781. }
  94782. };
  94783. /**
  94784. * Determine if a given mesh will be used in the glow layer
  94785. * @param mesh The mesh to test
  94786. * @returns true if the mesh will be highlighted by the current glow layer
  94787. */
  94788. GlowLayer.prototype.hasMesh = function (mesh) {
  94789. // Included Mesh
  94790. if (this._includedOnlyMeshes.length) {
  94791. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  94792. }
  94793. ;
  94794. // Excluded Mesh
  94795. if (this._excludedMeshes.length) {
  94796. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  94797. }
  94798. ;
  94799. return true;
  94800. };
  94801. /**
  94802. * Free any resources and references associated to a mesh.
  94803. * Internal use
  94804. * @param mesh The mesh to free.
  94805. */
  94806. GlowLayer.prototype._disposeMesh = function (mesh) {
  94807. this.removeIncludedOnlyMesh(mesh);
  94808. this.removeExcludedMesh(mesh);
  94809. };
  94810. /**
  94811. * Gets the class name of the effect layer
  94812. * @returns the string with the class name of the effect layer
  94813. */
  94814. GlowLayer.prototype.getClassName = function () {
  94815. return "GlowLayer";
  94816. };
  94817. /**
  94818. * Serializes this glow layer
  94819. * @returns a serialized glow layer object
  94820. */
  94821. GlowLayer.prototype.serialize = function () {
  94822. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94823. serializationObject.customType = "BABYLON.GlowLayer";
  94824. var index;
  94825. // Included meshes
  94826. serializationObject.includedMeshes = [];
  94827. if (this._includedOnlyMeshes.length) {
  94828. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  94829. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  94830. if (mesh) {
  94831. serializationObject.includedMeshes.push(mesh.id);
  94832. }
  94833. }
  94834. }
  94835. // Excluded meshes
  94836. serializationObject.excludedMeshes = [];
  94837. if (this._excludedMeshes.length) {
  94838. for (index = 0; index < this._excludedMeshes.length; index++) {
  94839. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  94840. if (mesh) {
  94841. serializationObject.excludedMeshes.push(mesh.id);
  94842. }
  94843. }
  94844. }
  94845. return serializationObject;
  94846. };
  94847. /**
  94848. * Creates a Glow Layer from parsed glow layer data
  94849. * @param parsedGlowLayer defines glow layer data
  94850. * @param scene defines the current scene
  94851. * @param rootUrl defines the root URL containing the glow layer information
  94852. * @returns a parsed Glow Layer
  94853. */
  94854. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  94855. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  94856. var index;
  94857. // Excluded meshes
  94858. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  94859. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  94860. if (mesh) {
  94861. gl.addExcludedMesh(mesh);
  94862. }
  94863. }
  94864. // Included meshes
  94865. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  94866. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  94867. if (mesh) {
  94868. gl.addIncludedOnlyMesh(mesh);
  94869. }
  94870. }
  94871. return gl;
  94872. };
  94873. /**
  94874. * Effect Name of the layer.
  94875. */
  94876. GlowLayer.EffectName = "GlowLayer";
  94877. /**
  94878. * The default blur kernel size used for the glow.
  94879. */
  94880. GlowLayer.DefaultBlurKernelSize = 32;
  94881. /**
  94882. * The default texture size ratio used for the glow.
  94883. */
  94884. GlowLayer.DefaultTextureRatio = 0.5;
  94885. __decorate([
  94886. BABYLON.serialize()
  94887. ], GlowLayer.prototype, "blurKernelSize", null);
  94888. __decorate([
  94889. BABYLON.serialize()
  94890. ], GlowLayer.prototype, "intensity", null);
  94891. __decorate([
  94892. BABYLON.serialize("options")
  94893. ], GlowLayer.prototype, "_options", void 0);
  94894. return GlowLayer;
  94895. }(BABYLON.EffectLayer));
  94896. BABYLON.GlowLayer = GlowLayer;
  94897. })(BABYLON || (BABYLON = {}));
  94898. //# sourceMappingURL=babylon.glowLayer.js.map
  94899. var BABYLON;
  94900. (function (BABYLON) {
  94901. /**
  94902. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  94903. */
  94904. var AssetTaskState;
  94905. (function (AssetTaskState) {
  94906. /**
  94907. * Initialization
  94908. */
  94909. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  94910. /**
  94911. * Running
  94912. */
  94913. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  94914. /**
  94915. * Done
  94916. */
  94917. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  94918. /**
  94919. * Error
  94920. */
  94921. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  94922. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  94923. /**
  94924. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  94925. */
  94926. var AbstractAssetTask = /** @class */ (function () {
  94927. /**
  94928. * Creates a new {BABYLON.AssetsManager}
  94929. * @param name defines the name of the task
  94930. */
  94931. function AbstractAssetTask(
  94932. /**
  94933. * Task name
  94934. */ name) {
  94935. this.name = name;
  94936. this._isCompleted = false;
  94937. this._taskState = AssetTaskState.INIT;
  94938. }
  94939. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  94940. /**
  94941. * Get if the task is completed
  94942. */
  94943. get: function () {
  94944. return this._isCompleted;
  94945. },
  94946. enumerable: true,
  94947. configurable: true
  94948. });
  94949. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  94950. /**
  94951. * Gets the current state of the task
  94952. */
  94953. get: function () {
  94954. return this._taskState;
  94955. },
  94956. enumerable: true,
  94957. configurable: true
  94958. });
  94959. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  94960. /**
  94961. * Gets the current error object (if task is in error)
  94962. */
  94963. get: function () {
  94964. return this._errorObject;
  94965. },
  94966. enumerable: true,
  94967. configurable: true
  94968. });
  94969. /**
  94970. * Internal only
  94971. * @hidden
  94972. */
  94973. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  94974. if (this._errorObject) {
  94975. return;
  94976. }
  94977. this._errorObject = {
  94978. message: message,
  94979. exception: exception
  94980. };
  94981. };
  94982. /**
  94983. * Execute the current task
  94984. * @param scene defines the scene where you want your assets to be loaded
  94985. * @param onSuccess is a callback called when the task is successfully executed
  94986. * @param onError is a callback called if an error occurs
  94987. */
  94988. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  94989. var _this = this;
  94990. this._taskState = AssetTaskState.RUNNING;
  94991. this.runTask(scene, function () {
  94992. _this.onDoneCallback(onSuccess, onError);
  94993. }, function (msg, exception) {
  94994. _this.onErrorCallback(onError, msg, exception);
  94995. });
  94996. };
  94997. /**
  94998. * Execute the current task
  94999. * @param scene defines the scene where you want your assets to be loaded
  95000. * @param onSuccess is a callback called when the task is successfully executed
  95001. * @param onError is a callback called if an error occurs
  95002. */
  95003. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95004. throw new Error("runTask is not implemented");
  95005. };
  95006. /**
  95007. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  95008. * This can be used with failed tasks that have the reason for failure fixed.
  95009. */
  95010. AbstractAssetTask.prototype.reset = function () {
  95011. this._taskState = AssetTaskState.INIT;
  95012. };
  95013. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  95014. this._taskState = AssetTaskState.ERROR;
  95015. this._errorObject = {
  95016. message: message,
  95017. exception: exception
  95018. };
  95019. if (this.onError) {
  95020. this.onError(this, message, exception);
  95021. }
  95022. onError();
  95023. };
  95024. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  95025. try {
  95026. this._taskState = AssetTaskState.DONE;
  95027. this._isCompleted = true;
  95028. if (this.onSuccess) {
  95029. this.onSuccess(this);
  95030. }
  95031. onSuccess();
  95032. }
  95033. catch (e) {
  95034. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  95035. }
  95036. };
  95037. return AbstractAssetTask;
  95038. }());
  95039. BABYLON.AbstractAssetTask = AbstractAssetTask;
  95040. /**
  95041. * Class used to share progress information about assets loading
  95042. */
  95043. var AssetsProgressEvent = /** @class */ (function () {
  95044. /**
  95045. * Creates a {BABYLON.AssetsProgressEvent}
  95046. * @param remainingCount defines the number of remaining tasks to process
  95047. * @param totalCount defines the total number of tasks
  95048. * @param task defines the task that was just processed
  95049. */
  95050. function AssetsProgressEvent(remainingCount, totalCount, task) {
  95051. this.remainingCount = remainingCount;
  95052. this.totalCount = totalCount;
  95053. this.task = task;
  95054. }
  95055. return AssetsProgressEvent;
  95056. }());
  95057. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  95058. /**
  95059. * Define a task used by {BABYLON.AssetsManager} to load meshes
  95060. */
  95061. var MeshAssetTask = /** @class */ (function (_super) {
  95062. __extends(MeshAssetTask, _super);
  95063. /**
  95064. * Creates a new {BABYLON.MeshAssetTask}
  95065. * @param name defines the name of the task
  95066. * @param meshesNames defines the list of mesh's names you want to load
  95067. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  95068. * @param sceneFilename defines the filename of the scene to load from
  95069. */
  95070. function MeshAssetTask(
  95071. /**
  95072. * Defines the name of the task
  95073. */
  95074. name,
  95075. /**
  95076. * Defines the list of mesh's names you want to load
  95077. */
  95078. meshesNames,
  95079. /**
  95080. * Defines the root url to use as a base to load your meshes and associated resources
  95081. */
  95082. rootUrl,
  95083. /**
  95084. * Defines the filename of the scene to load from
  95085. */
  95086. sceneFilename) {
  95087. var _this = _super.call(this, name) || this;
  95088. _this.name = name;
  95089. _this.meshesNames = meshesNames;
  95090. _this.rootUrl = rootUrl;
  95091. _this.sceneFilename = sceneFilename;
  95092. return _this;
  95093. }
  95094. /**
  95095. * Execute the current task
  95096. * @param scene defines the scene where you want your assets to be loaded
  95097. * @param onSuccess is a callback called when the task is successfully executed
  95098. * @param onError is a callback called if an error occurs
  95099. */
  95100. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95101. var _this = this;
  95102. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  95103. _this.loadedMeshes = meshes;
  95104. _this.loadedParticleSystems = particleSystems;
  95105. _this.loadedSkeletons = skeletons;
  95106. onSuccess();
  95107. }, null, function (scene, message, exception) {
  95108. onError(message, exception);
  95109. });
  95110. };
  95111. return MeshAssetTask;
  95112. }(AbstractAssetTask));
  95113. BABYLON.MeshAssetTask = MeshAssetTask;
  95114. /**
  95115. * Define a task used by {BABYLON.AssetsManager} to load text content
  95116. */
  95117. var TextFileAssetTask = /** @class */ (function (_super) {
  95118. __extends(TextFileAssetTask, _super);
  95119. /**
  95120. * Creates a new TextFileAssetTask object
  95121. * @param name defines the name of the task
  95122. * @param url defines the location of the file to load
  95123. */
  95124. function TextFileAssetTask(
  95125. /**
  95126. * Defines the name of the task
  95127. */
  95128. name,
  95129. /**
  95130. * Defines the location of the file to load
  95131. */
  95132. url) {
  95133. var _this = _super.call(this, name) || this;
  95134. _this.name = name;
  95135. _this.url = url;
  95136. return _this;
  95137. }
  95138. /**
  95139. * Execute the current task
  95140. * @param scene defines the scene where you want your assets to be loaded
  95141. * @param onSuccess is a callback called when the task is successfully executed
  95142. * @param onError is a callback called if an error occurs
  95143. */
  95144. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95145. var _this = this;
  95146. scene._loadFile(this.url, function (data) {
  95147. _this.text = data;
  95148. onSuccess();
  95149. }, undefined, false, false, function (request, exception) {
  95150. if (request) {
  95151. onError(request.status + " " + request.statusText, exception);
  95152. }
  95153. });
  95154. };
  95155. return TextFileAssetTask;
  95156. }(AbstractAssetTask));
  95157. BABYLON.TextFileAssetTask = TextFileAssetTask;
  95158. /**
  95159. * Define a task used by {BABYLON.AssetsManager} to load binary data
  95160. */
  95161. var BinaryFileAssetTask = /** @class */ (function (_super) {
  95162. __extends(BinaryFileAssetTask, _super);
  95163. /**
  95164. * Creates a new BinaryFileAssetTask object
  95165. * @param name defines the name of the new task
  95166. * @param url defines the location of the file to load
  95167. */
  95168. function BinaryFileAssetTask(
  95169. /**
  95170. * Defines the name of the task
  95171. */
  95172. name,
  95173. /**
  95174. * Defines the location of the file to load
  95175. */
  95176. url) {
  95177. var _this = _super.call(this, name) || this;
  95178. _this.name = name;
  95179. _this.url = url;
  95180. return _this;
  95181. }
  95182. /**
  95183. * Execute the current task
  95184. * @param scene defines the scene where you want your assets to be loaded
  95185. * @param onSuccess is a callback called when the task is successfully executed
  95186. * @param onError is a callback called if an error occurs
  95187. */
  95188. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95189. var _this = this;
  95190. scene._loadFile(this.url, function (data) {
  95191. _this.data = data;
  95192. onSuccess();
  95193. }, undefined, true, true, function (request, exception) {
  95194. if (request) {
  95195. onError(request.status + " " + request.statusText, exception);
  95196. }
  95197. });
  95198. };
  95199. return BinaryFileAssetTask;
  95200. }(AbstractAssetTask));
  95201. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  95202. /**
  95203. * Define a task used by {BABYLON.AssetsManager} to load images
  95204. */
  95205. var ImageAssetTask = /** @class */ (function (_super) {
  95206. __extends(ImageAssetTask, _super);
  95207. /**
  95208. * Creates a new ImageAssetTask
  95209. * @param name defines the name of the task
  95210. * @param url defines the location of the image to load
  95211. */
  95212. function ImageAssetTask(
  95213. /**
  95214. * Defines the name of the task
  95215. */
  95216. name,
  95217. /**
  95218. * Defines the location of the image to load
  95219. */
  95220. url) {
  95221. var _this = _super.call(this, name) || this;
  95222. _this.name = name;
  95223. _this.url = url;
  95224. return _this;
  95225. }
  95226. /**
  95227. * Execute the current task
  95228. * @param scene defines the scene where you want your assets to be loaded
  95229. * @param onSuccess is a callback called when the task is successfully executed
  95230. * @param onError is a callback called if an error occurs
  95231. */
  95232. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95233. var _this = this;
  95234. var img = new Image();
  95235. BABYLON.Tools.SetCorsBehavior(this.url, img);
  95236. img.onload = function () {
  95237. _this.image = img;
  95238. onSuccess();
  95239. };
  95240. img.onerror = function (err) {
  95241. onError("Error loading image", err);
  95242. };
  95243. img.src = this.url;
  95244. };
  95245. return ImageAssetTask;
  95246. }(AbstractAssetTask));
  95247. BABYLON.ImageAssetTask = ImageAssetTask;
  95248. /**
  95249. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  95250. */
  95251. var TextureAssetTask = /** @class */ (function (_super) {
  95252. __extends(TextureAssetTask, _super);
  95253. /**
  95254. * Creates a new TextureAssetTask object
  95255. * @param name defines the name of the task
  95256. * @param url defines the location of the file to load
  95257. * @param noMipmap defines if mipmap should not be generated (default is false)
  95258. * @param invertY defines if texture must be inverted on Y axis (default is false)
  95259. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95260. */
  95261. function TextureAssetTask(
  95262. /**
  95263. * Defines the name of the task
  95264. */
  95265. name,
  95266. /**
  95267. * Defines the location of the file to load
  95268. */
  95269. url,
  95270. /**
  95271. * Defines if mipmap should not be generated (default is false)
  95272. */
  95273. noMipmap,
  95274. /**
  95275. * Defines if texture must be inverted on Y axis (default is false)
  95276. */
  95277. invertY,
  95278. /**
  95279. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  95280. */
  95281. samplingMode) {
  95282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95283. var _this = _super.call(this, name) || this;
  95284. _this.name = name;
  95285. _this.url = url;
  95286. _this.noMipmap = noMipmap;
  95287. _this.invertY = invertY;
  95288. _this.samplingMode = samplingMode;
  95289. return _this;
  95290. }
  95291. /**
  95292. * Execute the current task
  95293. * @param scene defines the scene where you want your assets to be loaded
  95294. * @param onSuccess is a callback called when the task is successfully executed
  95295. * @param onError is a callback called if an error occurs
  95296. */
  95297. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95298. var onload = function () {
  95299. onSuccess();
  95300. };
  95301. var onerror = function (message, exception) {
  95302. onError(message, exception);
  95303. };
  95304. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  95305. };
  95306. return TextureAssetTask;
  95307. }(AbstractAssetTask));
  95308. BABYLON.TextureAssetTask = TextureAssetTask;
  95309. /**
  95310. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  95311. */
  95312. var CubeTextureAssetTask = /** @class */ (function (_super) {
  95313. __extends(CubeTextureAssetTask, _super);
  95314. /**
  95315. * Creates a new CubeTextureAssetTask
  95316. * @param name defines the name of the task
  95317. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95318. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95319. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95320. * @param files defines the explicit list of files (undefined by default)
  95321. */
  95322. function CubeTextureAssetTask(
  95323. /**
  95324. * Defines the name of the task
  95325. */
  95326. name,
  95327. /**
  95328. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  95329. */
  95330. url,
  95331. /**
  95332. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  95333. */
  95334. extensions,
  95335. /**
  95336. * Defines if mipmaps should not be generated (default is false)
  95337. */
  95338. noMipmap,
  95339. /**
  95340. * Defines the explicit list of files (undefined by default)
  95341. */
  95342. files) {
  95343. var _this = _super.call(this, name) || this;
  95344. _this.name = name;
  95345. _this.url = url;
  95346. _this.extensions = extensions;
  95347. _this.noMipmap = noMipmap;
  95348. _this.files = files;
  95349. return _this;
  95350. }
  95351. /**
  95352. * Execute the current task
  95353. * @param scene defines the scene where you want your assets to be loaded
  95354. * @param onSuccess is a callback called when the task is successfully executed
  95355. * @param onError is a callback called if an error occurs
  95356. */
  95357. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  95358. var onload = function () {
  95359. onSuccess();
  95360. };
  95361. var onerror = function (message, exception) {
  95362. onError(message, exception);
  95363. };
  95364. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  95365. };
  95366. return CubeTextureAssetTask;
  95367. }(AbstractAssetTask));
  95368. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  95369. /**
  95370. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  95371. */
  95372. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  95373. __extends(HDRCubeTextureAssetTask, _super);
  95374. /**
  95375. * Creates a new HDRCubeTextureAssetTask object
  95376. * @param name defines the name of the task
  95377. * @param url defines the location of the file to load
  95378. * @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.
  95379. * @param noMipmap defines if mipmaps should not be generated (default is false)
  95380. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95381. * @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)
  95382. * @param reserved Internal use only
  95383. */
  95384. function HDRCubeTextureAssetTask(
  95385. /**
  95386. * Defines the name of the task
  95387. */
  95388. name,
  95389. /**
  95390. * Defines the location of the file to load
  95391. */
  95392. url,
  95393. /**
  95394. * Defines the desired size (the more it increases the longer the generation will be)
  95395. */
  95396. size,
  95397. /**
  95398. * Defines if mipmaps should not be generated (default is false)
  95399. */
  95400. noMipmap,
  95401. /**
  95402. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  95403. */
  95404. generateHarmonics,
  95405. /**
  95406. * 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)
  95407. */
  95408. gammaSpace,
  95409. /**
  95410. * Internal Use Only
  95411. */
  95412. reserved) {
  95413. if (noMipmap === void 0) { noMipmap = false; }
  95414. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95415. if (gammaSpace === void 0) { gammaSpace = false; }
  95416. if (reserved === void 0) { reserved = false; }
  95417. var _this = _super.call(this, name) || this;
  95418. _this.name = name;
  95419. _this.url = url;
  95420. _this.size = size;
  95421. _this.noMipmap = noMipmap;
  95422. _this.generateHarmonics = generateHarmonics;
  95423. _this.gammaSpace = gammaSpace;
  95424. _this.reserved = reserved;
  95425. return _this;
  95426. }
  95427. /**
  95428. * Execute the current task
  95429. * @param scene defines the scene where you want your assets to be loaded
  95430. * @param onSuccess is a callback called when the task is successfully executed
  95431. * @param onError is a callback called if an error occurs
  95432. */
  95433. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  95434. var onload = function () {
  95435. onSuccess();
  95436. };
  95437. var onerror = function (message, exception) {
  95438. onError(message, exception);
  95439. };
  95440. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  95441. };
  95442. return HDRCubeTextureAssetTask;
  95443. }(AbstractAssetTask));
  95444. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  95445. /**
  95446. * This class can be used to easily import assets into a scene
  95447. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  95448. */
  95449. var AssetsManager = /** @class */ (function () {
  95450. /**
  95451. * Creates a new AssetsManager
  95452. * @param scene defines the scene to work on
  95453. */
  95454. function AssetsManager(scene) {
  95455. this._isLoading = false;
  95456. this._tasks = new Array();
  95457. this._waitingTasksCount = 0;
  95458. this._totalTasksCount = 0;
  95459. /**
  95460. * Observable called when all tasks are processed
  95461. */
  95462. this.onTaskSuccessObservable = new BABYLON.Observable();
  95463. /**
  95464. * Observable called when a task had an error
  95465. */
  95466. this.onTaskErrorObservable = new BABYLON.Observable();
  95467. /**
  95468. * Observable called when a task is successful
  95469. */
  95470. this.onTasksDoneObservable = new BABYLON.Observable();
  95471. /**
  95472. * Observable called when a task is done (whatever the result is)
  95473. */
  95474. this.onProgressObservable = new BABYLON.Observable();
  95475. /**
  95476. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  95477. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  95478. */
  95479. this.useDefaultLoadingScreen = true;
  95480. this._scene = scene;
  95481. }
  95482. /**
  95483. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  95484. * @param taskName defines the name of the new task
  95485. * @param meshesNames defines the name of meshes to load
  95486. * @param rootUrl defines the root url to use to locate files
  95487. * @param sceneFilename defines the filename of the scene file
  95488. * @returns a new {BABYLON.MeshAssetTask} object
  95489. */
  95490. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  95491. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  95492. this._tasks.push(task);
  95493. return task;
  95494. };
  95495. /**
  95496. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  95497. * @param taskName defines the name of the new task
  95498. * @param url defines the url of the file to load
  95499. * @returns a new {BABYLON.TextFileAssetTask} object
  95500. */
  95501. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  95502. var task = new TextFileAssetTask(taskName, url);
  95503. this._tasks.push(task);
  95504. return task;
  95505. };
  95506. /**
  95507. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  95508. * @param taskName defines the name of the new task
  95509. * @param url defines the url of the file to load
  95510. * @returns a new {BABYLON.BinaryFileAssetTask} object
  95511. */
  95512. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  95513. var task = new BinaryFileAssetTask(taskName, url);
  95514. this._tasks.push(task);
  95515. return task;
  95516. };
  95517. /**
  95518. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  95519. * @param taskName defines the name of the new task
  95520. * @param url defines the url of the file to load
  95521. * @returns a new {BABYLON.ImageAssetTask} object
  95522. */
  95523. AssetsManager.prototype.addImageTask = function (taskName, url) {
  95524. var task = new ImageAssetTask(taskName, url);
  95525. this._tasks.push(task);
  95526. return task;
  95527. };
  95528. /**
  95529. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  95530. * @param taskName defines the name of the new task
  95531. * @param url defines the url of the file to load
  95532. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95533. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  95534. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  95535. * @returns a new {BABYLON.TextureAssetTask} object
  95536. */
  95537. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  95538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95539. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  95540. this._tasks.push(task);
  95541. return task;
  95542. };
  95543. /**
  95544. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  95545. * @param taskName defines the name of the new task
  95546. * @param url defines the url of the file to load
  95547. * @param extensions defines the extension to use to load the cube map (can be null)
  95548. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95549. * @param files defines the list of files to load (can be null)
  95550. * @returns a new {BABYLON.CubeTextureAssetTask} object
  95551. */
  95552. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  95553. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  95554. this._tasks.push(task);
  95555. return task;
  95556. };
  95557. /**
  95558. *
  95559. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  95560. * @param taskName defines the name of the new task
  95561. * @param url defines the url of the file to load
  95562. * @param size defines the size you want for the cubemap (can be null)
  95563. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  95564. * @param generateHarmonics defines if you want to automatically generate (true by default)
  95565. * @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)
  95566. * @param reserved Internal use only
  95567. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  95568. */
  95569. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  95570. if (noMipmap === void 0) { noMipmap = false; }
  95571. if (generateHarmonics === void 0) { generateHarmonics = true; }
  95572. if (gammaSpace === void 0) { gammaSpace = false; }
  95573. if (reserved === void 0) { reserved = false; }
  95574. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  95575. this._tasks.push(task);
  95576. return task;
  95577. };
  95578. /**
  95579. * Remove a task from the assets manager.
  95580. * @param task the task to remove
  95581. */
  95582. AssetsManager.prototype.removeTask = function (task) {
  95583. var index = this._tasks.indexOf(task);
  95584. if (index > -1) {
  95585. this._tasks.splice(index, 1);
  95586. }
  95587. };
  95588. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  95589. this._waitingTasksCount--;
  95590. try {
  95591. if (this.onProgress) {
  95592. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  95593. }
  95594. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  95595. }
  95596. catch (e) {
  95597. BABYLON.Tools.Error("Error running progress callbacks.");
  95598. console.log(e);
  95599. }
  95600. if (this._waitingTasksCount === 0) {
  95601. try {
  95602. if (this.onFinish) {
  95603. this.onFinish(this._tasks);
  95604. }
  95605. // Let's remove successfull tasks
  95606. var currentTasks = this._tasks.slice();
  95607. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  95608. var task = currentTasks_1[_i];
  95609. if (task.taskState === AssetTaskState.DONE) {
  95610. var index = this._tasks.indexOf(task);
  95611. if (index > -1) {
  95612. this._tasks.splice(index, 1);
  95613. }
  95614. }
  95615. }
  95616. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95617. }
  95618. catch (e) {
  95619. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  95620. console.log(e);
  95621. }
  95622. this._isLoading = false;
  95623. this._scene.getEngine().hideLoadingUI();
  95624. }
  95625. };
  95626. AssetsManager.prototype._runTask = function (task) {
  95627. var _this = this;
  95628. var done = function () {
  95629. try {
  95630. if (_this.onTaskSuccess) {
  95631. _this.onTaskSuccess(task);
  95632. }
  95633. _this.onTaskSuccessObservable.notifyObservers(task);
  95634. _this._decreaseWaitingTasksCount(task);
  95635. }
  95636. catch (e) {
  95637. error("Error executing task success callbacks", e);
  95638. }
  95639. };
  95640. var error = function (message, exception) {
  95641. task._setErrorObject(message, exception);
  95642. if (_this.onTaskError) {
  95643. _this.onTaskError(task);
  95644. }
  95645. _this.onTaskErrorObservable.notifyObservers(task);
  95646. _this._decreaseWaitingTasksCount(task);
  95647. };
  95648. task.run(this._scene, done, error);
  95649. };
  95650. /**
  95651. * Reset the {BABYLON.AssetsManager} and remove all tasks
  95652. * @return the current instance of the {BABYLON.AssetsManager}
  95653. */
  95654. AssetsManager.prototype.reset = function () {
  95655. this._isLoading = false;
  95656. this._tasks = new Array();
  95657. return this;
  95658. };
  95659. /**
  95660. * Start the loading process
  95661. * @return the current instance of the {BABYLON.AssetsManager}
  95662. */
  95663. AssetsManager.prototype.load = function () {
  95664. if (this._isLoading) {
  95665. return this;
  95666. }
  95667. this._isLoading = true;
  95668. this._waitingTasksCount = this._tasks.length;
  95669. this._totalTasksCount = this._tasks.length;
  95670. if (this._waitingTasksCount === 0) {
  95671. this._isLoading = false;
  95672. if (this.onFinish) {
  95673. this.onFinish(this._tasks);
  95674. }
  95675. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95676. return this;
  95677. }
  95678. if (this.useDefaultLoadingScreen) {
  95679. this._scene.getEngine().displayLoadingUI();
  95680. }
  95681. for (var index = 0; index < this._tasks.length; index++) {
  95682. var task = this._tasks[index];
  95683. if (task.taskState === AssetTaskState.INIT) {
  95684. this._runTask(task);
  95685. }
  95686. }
  95687. return this;
  95688. };
  95689. return AssetsManager;
  95690. }());
  95691. BABYLON.AssetsManager = AssetsManager;
  95692. })(BABYLON || (BABYLON = {}));
  95693. //# sourceMappingURL=babylon.assetsManager.js.map
  95694. var BABYLON;
  95695. (function (BABYLON) {
  95696. var serializedGeometries = [];
  95697. var serializeGeometry = function (geometry, serializationGeometries) {
  95698. if (serializedGeometries[geometry.id]) {
  95699. return;
  95700. }
  95701. if (geometry.doNotSerialize) {
  95702. return;
  95703. }
  95704. if (geometry instanceof BABYLON.BoxGeometry) {
  95705. serializationGeometries.boxes.push(geometry.serialize());
  95706. }
  95707. else if (geometry instanceof BABYLON.SphereGeometry) {
  95708. serializationGeometries.spheres.push(geometry.serialize());
  95709. }
  95710. else if (geometry instanceof BABYLON.CylinderGeometry) {
  95711. serializationGeometries.cylinders.push(geometry.serialize());
  95712. }
  95713. else if (geometry instanceof BABYLON.TorusGeometry) {
  95714. serializationGeometries.toruses.push(geometry.serialize());
  95715. }
  95716. else if (geometry instanceof BABYLON.GroundGeometry) {
  95717. serializationGeometries.grounds.push(geometry.serialize());
  95718. }
  95719. else if (geometry instanceof BABYLON.Plane) {
  95720. serializationGeometries.planes.push(geometry.serialize());
  95721. }
  95722. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  95723. serializationGeometries.torusKnots.push(geometry.serialize());
  95724. }
  95725. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  95726. throw new Error("Unknown primitive type");
  95727. }
  95728. else {
  95729. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  95730. }
  95731. serializedGeometries[geometry.id] = true;
  95732. };
  95733. var serializeMesh = function (mesh, serializationScene) {
  95734. var serializationObject = {};
  95735. // Geometry
  95736. var geometry = mesh._geometry;
  95737. if (geometry) {
  95738. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  95739. // 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
  95740. serializeGeometry(geometry, serializationScene.geometries);
  95741. }
  95742. }
  95743. // Custom
  95744. if (mesh.serialize) {
  95745. mesh.serialize(serializationObject);
  95746. }
  95747. return serializationObject;
  95748. };
  95749. var finalizeSingleMesh = function (mesh, serializationObject) {
  95750. //only works if the mesh is already loaded
  95751. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95752. //serialize material
  95753. if (mesh.material) {
  95754. if (mesh.material instanceof BABYLON.MultiMaterial) {
  95755. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  95756. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95757. serializationObject.multiMaterials.push(mesh.material.serialize());
  95758. }
  95759. }
  95760. else {
  95761. serializationObject.materials = serializationObject.materials || [];
  95762. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95763. serializationObject.materials.push(mesh.material.serialize());
  95764. }
  95765. }
  95766. }
  95767. //serialize geometry
  95768. var geometry = mesh._geometry;
  95769. if (geometry) {
  95770. if (!serializationObject.geometries) {
  95771. serializationObject.geometries = {};
  95772. serializationObject.geometries.boxes = [];
  95773. serializationObject.geometries.spheres = [];
  95774. serializationObject.geometries.cylinders = [];
  95775. serializationObject.geometries.toruses = [];
  95776. serializationObject.geometries.grounds = [];
  95777. serializationObject.geometries.planes = [];
  95778. serializationObject.geometries.torusKnots = [];
  95779. serializationObject.geometries.vertexData = [];
  95780. }
  95781. serializeGeometry(geometry, serializationObject.geometries);
  95782. }
  95783. // Skeletons
  95784. if (mesh.skeleton) {
  95785. serializationObject.skeletons = serializationObject.skeletons || [];
  95786. serializationObject.skeletons.push(mesh.skeleton.serialize());
  95787. }
  95788. //serialize the actual mesh
  95789. serializationObject.meshes = serializationObject.meshes || [];
  95790. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95791. }
  95792. };
  95793. var SceneSerializer = /** @class */ (function () {
  95794. function SceneSerializer() {
  95795. }
  95796. SceneSerializer.ClearCache = function () {
  95797. serializedGeometries = [];
  95798. };
  95799. SceneSerializer.Serialize = function (scene) {
  95800. var serializationObject = {};
  95801. SceneSerializer.ClearCache();
  95802. // Scene
  95803. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  95804. serializationObject.autoClear = scene.autoClear;
  95805. serializationObject.clearColor = scene.clearColor.asArray();
  95806. serializationObject.ambientColor = scene.ambientColor.asArray();
  95807. serializationObject.gravity = scene.gravity.asArray();
  95808. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  95809. serializationObject.workerCollisions = scene.workerCollisions;
  95810. // Fog
  95811. if (scene.fogMode && scene.fogMode !== 0) {
  95812. serializationObject.fogMode = scene.fogMode;
  95813. serializationObject.fogColor = scene.fogColor.asArray();
  95814. serializationObject.fogStart = scene.fogStart;
  95815. serializationObject.fogEnd = scene.fogEnd;
  95816. serializationObject.fogDensity = scene.fogDensity;
  95817. }
  95818. //Physics
  95819. if (scene.isPhysicsEnabled()) {
  95820. var physicEngine = scene.getPhysicsEngine();
  95821. if (physicEngine) {
  95822. serializationObject.physicsEnabled = true;
  95823. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  95824. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  95825. }
  95826. }
  95827. // Metadata
  95828. if (scene.metadata) {
  95829. serializationObject.metadata = scene.metadata;
  95830. }
  95831. // Morph targets
  95832. serializationObject.morphTargetManagers = [];
  95833. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  95834. var abstractMesh = _a[_i];
  95835. var manager = abstractMesh.morphTargetManager;
  95836. if (manager) {
  95837. serializationObject.morphTargetManagers.push(manager.serialize());
  95838. }
  95839. }
  95840. // Lights
  95841. serializationObject.lights = [];
  95842. var index;
  95843. var light;
  95844. for (index = 0; index < scene.lights.length; index++) {
  95845. light = scene.lights[index];
  95846. if (!light.doNotSerialize) {
  95847. serializationObject.lights.push(light.serialize());
  95848. }
  95849. }
  95850. // Cameras
  95851. serializationObject.cameras = [];
  95852. for (index = 0; index < scene.cameras.length; index++) {
  95853. var camera = scene.cameras[index];
  95854. if (!camera.doNotSerialize) {
  95855. serializationObject.cameras.push(camera.serialize());
  95856. }
  95857. }
  95858. if (scene.activeCamera) {
  95859. serializationObject.activeCameraID = scene.activeCamera.id;
  95860. }
  95861. // Animations
  95862. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  95863. // Materials
  95864. serializationObject.materials = [];
  95865. serializationObject.multiMaterials = [];
  95866. var material;
  95867. for (index = 0; index < scene.materials.length; index++) {
  95868. material = scene.materials[index];
  95869. if (!material.doNotSerialize) {
  95870. serializationObject.materials.push(material.serialize());
  95871. }
  95872. }
  95873. // MultiMaterials
  95874. serializationObject.multiMaterials = [];
  95875. for (index = 0; index < scene.multiMaterials.length; index++) {
  95876. var multiMaterial = scene.multiMaterials[index];
  95877. serializationObject.multiMaterials.push(multiMaterial.serialize());
  95878. }
  95879. // Environment texture
  95880. if (scene.environmentTexture) {
  95881. serializationObject.environmentTexture = scene.environmentTexture.name;
  95882. }
  95883. // Skeletons
  95884. serializationObject.skeletons = [];
  95885. for (index = 0; index < scene.skeletons.length; index++) {
  95886. var skeleton = scene.skeletons[index];
  95887. if (!skeleton.doNotSerialize) {
  95888. serializationObject.skeletons.push(skeleton.serialize());
  95889. }
  95890. }
  95891. // Transform nodes
  95892. serializationObject.transformNodes = [];
  95893. for (index = 0; index < scene.transformNodes.length; index++) {
  95894. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  95895. }
  95896. // Geometries
  95897. serializationObject.geometries = {};
  95898. serializationObject.geometries.boxes = [];
  95899. serializationObject.geometries.spheres = [];
  95900. serializationObject.geometries.cylinders = [];
  95901. serializationObject.geometries.toruses = [];
  95902. serializationObject.geometries.grounds = [];
  95903. serializationObject.geometries.planes = [];
  95904. serializationObject.geometries.torusKnots = [];
  95905. serializationObject.geometries.vertexData = [];
  95906. serializedGeometries = [];
  95907. var geometries = scene.getGeometries();
  95908. for (index = 0; index < geometries.length; index++) {
  95909. var geometry = geometries[index];
  95910. if (geometry.isReady()) {
  95911. serializeGeometry(geometry, serializationObject.geometries);
  95912. }
  95913. }
  95914. // Meshes
  95915. serializationObject.meshes = [];
  95916. for (index = 0; index < scene.meshes.length; index++) {
  95917. var abstractMesh = scene.meshes[index];
  95918. if (abstractMesh instanceof BABYLON.Mesh) {
  95919. var mesh = abstractMesh;
  95920. if (!mesh.doNotSerialize) {
  95921. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95922. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95923. }
  95924. }
  95925. }
  95926. }
  95927. // Particles Systems
  95928. serializationObject.particleSystems = [];
  95929. for (index = 0; index < scene.particleSystems.length; index++) {
  95930. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  95931. }
  95932. // Lens flares
  95933. serializationObject.lensFlareSystems = [];
  95934. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  95935. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  95936. }
  95937. // Shadows
  95938. serializationObject.shadowGenerators = [];
  95939. for (index = 0; index < scene.lights.length; index++) {
  95940. light = scene.lights[index];
  95941. var shadowGenerator = light.getShadowGenerator();
  95942. if (shadowGenerator) {
  95943. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  95944. }
  95945. }
  95946. // Action Manager
  95947. if (scene.actionManager) {
  95948. serializationObject.actions = scene.actionManager.serialize("scene");
  95949. }
  95950. // Audio
  95951. serializationObject.sounds = [];
  95952. for (index = 0; index < scene.soundTracks.length; index++) {
  95953. var soundtrack = scene.soundTracks[index];
  95954. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  95955. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  95956. }
  95957. }
  95958. // Effect layers
  95959. serializationObject.effectLayers = [];
  95960. for (index = 0; index < scene.effectLayers.length; index++) {
  95961. var layer = scene.effectLayers[index];
  95962. if (layer.serialize) {
  95963. serializationObject.effectLayers.push(layer.serialize());
  95964. }
  95965. }
  95966. return serializationObject;
  95967. };
  95968. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  95969. if (withParents === void 0) { withParents = false; }
  95970. if (withChildren === void 0) { withChildren = false; }
  95971. var serializationObject = {};
  95972. SceneSerializer.ClearCache();
  95973. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  95974. if (withParents || withChildren) {
  95975. //deliberate for loop! not for each, appended should be processed as well.
  95976. for (var i = 0; i < toSerialize.length; ++i) {
  95977. if (withChildren) {
  95978. toSerialize[i].getDescendants().forEach(function (node) {
  95979. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  95980. toSerialize.push(node);
  95981. }
  95982. });
  95983. }
  95984. //make sure the array doesn't contain the object already
  95985. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  95986. toSerialize.push(toSerialize[i].parent);
  95987. }
  95988. }
  95989. }
  95990. toSerialize.forEach(function (mesh) {
  95991. finalizeSingleMesh(mesh, serializationObject);
  95992. });
  95993. return serializationObject;
  95994. };
  95995. return SceneSerializer;
  95996. }());
  95997. BABYLON.SceneSerializer = SceneSerializer;
  95998. })(BABYLON || (BABYLON = {}));
  95999. //# sourceMappingURL=babylon.sceneSerializer.js.map
  96000. var BABYLON;
  96001. (function (BABYLON) {
  96002. var ReflectionProbe = /** @class */ (function () {
  96003. function ReflectionProbe(name, size, scene, generateMipMaps) {
  96004. if (generateMipMaps === void 0) { generateMipMaps = true; }
  96005. var _this = this;
  96006. this.name = name;
  96007. this._viewMatrix = BABYLON.Matrix.Identity();
  96008. this._target = BABYLON.Vector3.Zero();
  96009. this._add = BABYLON.Vector3.Zero();
  96010. this._invertYAxis = false;
  96011. this.position = BABYLON.Vector3.Zero();
  96012. this._scene = scene;
  96013. this._scene.reflectionProbes.push(this);
  96014. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  96015. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  96016. switch (faceIndex) {
  96017. case 0:
  96018. _this._add.copyFromFloats(1, 0, 0);
  96019. break;
  96020. case 1:
  96021. _this._add.copyFromFloats(-1, 0, 0);
  96022. break;
  96023. case 2:
  96024. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  96025. break;
  96026. case 3:
  96027. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  96028. break;
  96029. case 4:
  96030. _this._add.copyFromFloats(0, 0, 1);
  96031. break;
  96032. case 5:
  96033. _this._add.copyFromFloats(0, 0, -1);
  96034. break;
  96035. }
  96036. if (_this._attachedMesh) {
  96037. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  96038. }
  96039. _this.position.addToRef(_this._add, _this._target);
  96040. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  96041. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  96042. scene._forcedViewPosition = _this.position;
  96043. });
  96044. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  96045. scene._forcedViewPosition = null;
  96046. scene.updateTransformMatrix(true);
  96047. });
  96048. if (scene.activeCamera) {
  96049. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  96050. }
  96051. }
  96052. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  96053. get: function () {
  96054. return this._renderTargetTexture.samples;
  96055. },
  96056. set: function (value) {
  96057. this._renderTargetTexture.samples = value;
  96058. },
  96059. enumerable: true,
  96060. configurable: true
  96061. });
  96062. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  96063. get: function () {
  96064. return this._renderTargetTexture.refreshRate;
  96065. },
  96066. set: function (value) {
  96067. this._renderTargetTexture.refreshRate = value;
  96068. },
  96069. enumerable: true,
  96070. configurable: true
  96071. });
  96072. ReflectionProbe.prototype.getScene = function () {
  96073. return this._scene;
  96074. };
  96075. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  96076. get: function () {
  96077. return this._renderTargetTexture;
  96078. },
  96079. enumerable: true,
  96080. configurable: true
  96081. });
  96082. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  96083. get: function () {
  96084. return this._renderTargetTexture.renderList;
  96085. },
  96086. enumerable: true,
  96087. configurable: true
  96088. });
  96089. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  96090. this._attachedMesh = mesh;
  96091. };
  96092. /**
  96093. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  96094. *
  96095. * @param renderingGroupId The rendering group id corresponding to its index
  96096. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  96097. */
  96098. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  96099. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  96100. };
  96101. ReflectionProbe.prototype.dispose = function () {
  96102. var index = this._scene.reflectionProbes.indexOf(this);
  96103. if (index !== -1) {
  96104. // Remove from the scene if found
  96105. this._scene.reflectionProbes.splice(index, 1);
  96106. }
  96107. if (this._renderTargetTexture) {
  96108. this._renderTargetTexture.dispose();
  96109. this._renderTargetTexture = null;
  96110. }
  96111. };
  96112. return ReflectionProbe;
  96113. }());
  96114. BABYLON.ReflectionProbe = ReflectionProbe;
  96115. })(BABYLON || (BABYLON = {}));
  96116. //# sourceMappingURL=babylon.reflectionProbe.js.map
  96117. var BABYLON;
  96118. (function (BABYLON) {
  96119. var Layer = /** @class */ (function () {
  96120. function Layer(name, imgUrl, scene, isBackground, color) {
  96121. this.name = name;
  96122. this.scale = new BABYLON.Vector2(1, 1);
  96123. this.offset = new BABYLON.Vector2(0, 0);
  96124. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  96125. this.layerMask = 0x0FFFFFFF;
  96126. this._vertexBuffers = {};
  96127. // Events
  96128. /**
  96129. * An event triggered when the layer is disposed.
  96130. */
  96131. this.onDisposeObservable = new BABYLON.Observable();
  96132. /**
  96133. * An event triggered before rendering the scene
  96134. */
  96135. this.onBeforeRenderObservable = new BABYLON.Observable();
  96136. /**
  96137. * An event triggered after rendering the scene
  96138. */
  96139. this.onAfterRenderObservable = new BABYLON.Observable();
  96140. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  96141. this.isBackground = isBackground === undefined ? true : isBackground;
  96142. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  96143. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  96144. this._scene.layers.push(this);
  96145. var engine = this._scene.getEngine();
  96146. // VBO
  96147. var vertices = [];
  96148. vertices.push(1, 1);
  96149. vertices.push(-1, 1);
  96150. vertices.push(-1, -1);
  96151. vertices.push(1, -1);
  96152. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96153. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96154. this._createIndexBuffer();
  96155. // Effects
  96156. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  96157. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  96158. }
  96159. Object.defineProperty(Layer.prototype, "onDispose", {
  96160. set: function (callback) {
  96161. if (this._onDisposeObserver) {
  96162. this.onDisposeObservable.remove(this._onDisposeObserver);
  96163. }
  96164. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  96165. },
  96166. enumerable: true,
  96167. configurable: true
  96168. });
  96169. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  96170. set: function (callback) {
  96171. if (this._onBeforeRenderObserver) {
  96172. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  96173. }
  96174. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  96175. },
  96176. enumerable: true,
  96177. configurable: true
  96178. });
  96179. Object.defineProperty(Layer.prototype, "onAfterRender", {
  96180. set: function (callback) {
  96181. if (this._onAfterRenderObserver) {
  96182. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96183. }
  96184. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  96185. },
  96186. enumerable: true,
  96187. configurable: true
  96188. });
  96189. Layer.prototype._createIndexBuffer = function () {
  96190. var engine = this._scene.getEngine();
  96191. // Indices
  96192. var indices = [];
  96193. indices.push(0);
  96194. indices.push(1);
  96195. indices.push(2);
  96196. indices.push(0);
  96197. indices.push(2);
  96198. indices.push(3);
  96199. this._indexBuffer = engine.createIndexBuffer(indices);
  96200. };
  96201. Layer.prototype._rebuild = function () {
  96202. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96203. if (vb) {
  96204. vb._rebuild();
  96205. }
  96206. this._createIndexBuffer();
  96207. };
  96208. Layer.prototype.render = function () {
  96209. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  96210. // Check
  96211. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  96212. return;
  96213. var engine = this._scene.getEngine();
  96214. this.onBeforeRenderObservable.notifyObservers(this);
  96215. // Render
  96216. engine.enableEffect(currentEffect);
  96217. engine.setState(false);
  96218. // Texture
  96219. currentEffect.setTexture("textureSampler", this.texture);
  96220. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  96221. // Color
  96222. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  96223. // Scale / offset
  96224. currentEffect.setVector2("offset", this.offset);
  96225. currentEffect.setVector2("scale", this.scale);
  96226. // VBOs
  96227. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96228. // Draw order
  96229. if (!this.alphaTest) {
  96230. engine.setAlphaMode(this.alphaBlendingMode);
  96231. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96232. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  96233. }
  96234. else {
  96235. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96236. }
  96237. this.onAfterRenderObservable.notifyObservers(this);
  96238. };
  96239. Layer.prototype.dispose = function () {
  96240. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96241. if (vertexBuffer) {
  96242. vertexBuffer.dispose();
  96243. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96244. }
  96245. if (this._indexBuffer) {
  96246. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96247. this._indexBuffer = null;
  96248. }
  96249. if (this.texture) {
  96250. this.texture.dispose();
  96251. this.texture = null;
  96252. }
  96253. // Remove from scene
  96254. var index = this._scene.layers.indexOf(this);
  96255. this._scene.layers.splice(index, 1);
  96256. // Callback
  96257. this.onDisposeObservable.notifyObservers(this);
  96258. this.onDisposeObservable.clear();
  96259. this.onAfterRenderObservable.clear();
  96260. this.onBeforeRenderObservable.clear();
  96261. };
  96262. return Layer;
  96263. }());
  96264. BABYLON.Layer = Layer;
  96265. })(BABYLON || (BABYLON = {}));
  96266. //# sourceMappingURL=babylon.layer.js.map
  96267. var BABYLON;
  96268. (function (BABYLON) {
  96269. var TextureTools = /** @class */ (function () {
  96270. function TextureTools() {
  96271. }
  96272. /**
  96273. * Uses the GPU to create a copy texture rescaled at a given size
  96274. * @param texture Texture to copy from
  96275. * @param width Desired width
  96276. * @param height Desired height
  96277. * @return Generated texture
  96278. */
  96279. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  96280. if (useBilinearMode === void 0) { useBilinearMode = true; }
  96281. var scene = texture.getScene();
  96282. var engine = scene.getEngine();
  96283. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  96284. rtt.wrapU = texture.wrapU;
  96285. rtt.wrapV = texture.wrapV;
  96286. rtt.uOffset = texture.uOffset;
  96287. rtt.vOffset = texture.vOffset;
  96288. rtt.uScale = texture.uScale;
  96289. rtt.vScale = texture.vScale;
  96290. rtt.uAng = texture.uAng;
  96291. rtt.vAng = texture.vAng;
  96292. rtt.wAng = texture.wAng;
  96293. rtt.coordinatesIndex = texture.coordinatesIndex;
  96294. rtt.level = texture.level;
  96295. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  96296. rtt._texture.isReady = false;
  96297. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96298. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96299. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96300. passPostProcess.getEffect().executeWhenCompiled(function () {
  96301. passPostProcess.onApply = function (effect) {
  96302. effect.setTexture("textureSampler", texture);
  96303. };
  96304. var internalTexture = rtt.getInternalTexture();
  96305. if (internalTexture) {
  96306. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  96307. engine.unBindFramebuffer(internalTexture);
  96308. rtt.disposeFramebufferObjects();
  96309. passPostProcess.dispose();
  96310. internalTexture.isReady = true;
  96311. }
  96312. });
  96313. return rtt;
  96314. };
  96315. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  96316. if (!scene._environmentBRDFTexture) {
  96317. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96318. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96319. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96320. scene._environmentBRDFTexture = texture;
  96321. }
  96322. return scene._environmentBRDFTexture;
  96323. };
  96324. 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=";
  96325. return TextureTools;
  96326. }());
  96327. BABYLON.TextureTools = TextureTools;
  96328. })(BABYLON || (BABYLON = {}));
  96329. //# sourceMappingURL=babylon.textureTools.js.map
  96330. var BABYLON;
  96331. (function (BABYLON) {
  96332. var FramingBehavior = /** @class */ (function () {
  96333. function FramingBehavior() {
  96334. this._mode = FramingBehavior.FitFrustumSidesMode;
  96335. this._radiusScale = 1.0;
  96336. this._positionScale = 0.5;
  96337. this._defaultElevation = 0.3;
  96338. this._elevationReturnTime = 1500;
  96339. this._elevationReturnWaitTime = 1000;
  96340. this._zoomStopsAnimation = false;
  96341. this._framingTime = 1500;
  96342. this._isPointerDown = false;
  96343. this._lastInteractionTime = -Infinity;
  96344. // Framing control
  96345. this._animatables = new Array();
  96346. this._betaIsAnimating = false;
  96347. }
  96348. Object.defineProperty(FramingBehavior.prototype, "name", {
  96349. get: function () {
  96350. return "Framing";
  96351. },
  96352. enumerable: true,
  96353. configurable: true
  96354. });
  96355. Object.defineProperty(FramingBehavior.prototype, "mode", {
  96356. /**
  96357. * Gets current mode used by the behavior.
  96358. */
  96359. get: function () {
  96360. return this._mode;
  96361. },
  96362. /**
  96363. * Sets the current mode used by the behavior
  96364. */
  96365. set: function (mode) {
  96366. this._mode = mode;
  96367. },
  96368. enumerable: true,
  96369. configurable: true
  96370. });
  96371. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  96372. /**
  96373. * Gets the scale applied to the radius
  96374. */
  96375. get: function () {
  96376. return this._radiusScale;
  96377. },
  96378. /**
  96379. * Sets the scale applied to the radius (1 by default)
  96380. */
  96381. set: function (radius) {
  96382. this._radiusScale = radius;
  96383. },
  96384. enumerable: true,
  96385. configurable: true
  96386. });
  96387. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  96388. /**
  96389. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96390. */
  96391. get: function () {
  96392. return this._positionScale;
  96393. },
  96394. /**
  96395. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  96396. */
  96397. set: function (scale) {
  96398. this._positionScale = scale;
  96399. },
  96400. enumerable: true,
  96401. configurable: true
  96402. });
  96403. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  96404. /**
  96405. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96406. * behaviour is triggered, in radians.
  96407. */
  96408. get: function () {
  96409. return this._defaultElevation;
  96410. },
  96411. /**
  96412. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  96413. * behaviour is triggered, in radians.
  96414. */
  96415. set: function (elevation) {
  96416. this._defaultElevation = elevation;
  96417. },
  96418. enumerable: true,
  96419. configurable: true
  96420. });
  96421. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  96422. /**
  96423. * Gets the time (in milliseconds) taken to return to the default beta position.
  96424. * Negative value indicates camera should not return to default.
  96425. */
  96426. get: function () {
  96427. return this._elevationReturnTime;
  96428. },
  96429. /**
  96430. * Sets the time (in milliseconds) taken to return to the default beta position.
  96431. * Negative value indicates camera should not return to default.
  96432. */
  96433. set: function (speed) {
  96434. this._elevationReturnTime = speed;
  96435. },
  96436. enumerable: true,
  96437. configurable: true
  96438. });
  96439. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  96440. /**
  96441. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96442. */
  96443. get: function () {
  96444. return this._elevationReturnWaitTime;
  96445. },
  96446. /**
  96447. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  96448. */
  96449. set: function (time) {
  96450. this._elevationReturnWaitTime = time;
  96451. },
  96452. enumerable: true,
  96453. configurable: true
  96454. });
  96455. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  96456. /**
  96457. * Gets the flag that indicates if user zooming should stop animation.
  96458. */
  96459. get: function () {
  96460. return this._zoomStopsAnimation;
  96461. },
  96462. /**
  96463. * Sets the flag that indicates if user zooming should stop animation.
  96464. */
  96465. set: function (flag) {
  96466. this._zoomStopsAnimation = flag;
  96467. },
  96468. enumerable: true,
  96469. configurable: true
  96470. });
  96471. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  96472. /**
  96473. * Gets the transition time when framing the mesh, in milliseconds
  96474. */
  96475. get: function () {
  96476. return this._framingTime;
  96477. },
  96478. /**
  96479. * Sets the transition time when framing the mesh, in milliseconds
  96480. */
  96481. set: function (time) {
  96482. this._framingTime = time;
  96483. },
  96484. enumerable: true,
  96485. configurable: true
  96486. });
  96487. FramingBehavior.prototype.init = function () {
  96488. // Do notihng
  96489. };
  96490. FramingBehavior.prototype.attach = function (camera) {
  96491. var _this = this;
  96492. this._attachedCamera = camera;
  96493. var scene = this._attachedCamera.getScene();
  96494. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  96495. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96496. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96497. _this._isPointerDown = true;
  96498. return;
  96499. }
  96500. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96501. _this._isPointerDown = false;
  96502. }
  96503. });
  96504. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96505. if (mesh) {
  96506. _this.zoomOnMesh(mesh);
  96507. }
  96508. });
  96509. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96510. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96511. _this._applyUserInteraction();
  96512. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  96513. // back to the default position after a given timeout
  96514. _this._maintainCameraAboveGround();
  96515. });
  96516. };
  96517. FramingBehavior.prototype.detach = function () {
  96518. if (!this._attachedCamera) {
  96519. return;
  96520. }
  96521. var scene = this._attachedCamera.getScene();
  96522. if (this._onPrePointerObservableObserver) {
  96523. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96524. }
  96525. if (this._onAfterCheckInputsObserver) {
  96526. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96527. }
  96528. if (this._onMeshTargetChangedObserver) {
  96529. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96530. }
  96531. this._attachedCamera = null;
  96532. };
  96533. /**
  96534. * Targets the given mesh and updates zoom level accordingly.
  96535. * @param mesh The mesh to target.
  96536. * @param radius Optional. If a cached radius position already exists, overrides default.
  96537. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96538. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96539. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96540. */
  96541. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96542. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96543. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96544. mesh.computeWorldMatrix(true);
  96545. var boundingBox = mesh.getBoundingInfo().boundingBox;
  96546. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  96547. };
  96548. /**
  96549. * Targets the given mesh with its children and updates zoom level accordingly.
  96550. * @param mesh The mesh to target.
  96551. * @param radius Optional. If a cached radius position already exists, overrides default.
  96552. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96553. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96554. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96555. */
  96556. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  96557. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96558. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96559. mesh.computeWorldMatrix(true);
  96560. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  96561. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  96562. };
  96563. /**
  96564. * Targets the given meshes with their children and updates zoom level accordingly.
  96565. * @param meshes The mesh to target.
  96566. * @param radius Optional. If a cached radius position already exists, overrides default.
  96567. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96568. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96569. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96570. */
  96571. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  96572. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96573. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96574. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  96575. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  96576. for (var i = 0; i < meshes.length; i++) {
  96577. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  96578. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  96579. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  96580. }
  96581. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  96582. };
  96583. /**
  96584. * Targets the given mesh and updates zoom level accordingly.
  96585. * @param mesh The mesh to target.
  96586. * @param radius Optional. If a cached radius position already exists, overrides default.
  96587. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  96588. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  96589. * @param onAnimationEnd Callback triggered at the end of the framing animation
  96590. */
  96591. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  96592. var _this = this;
  96593. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  96594. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  96595. var zoomTarget;
  96596. if (!this._attachedCamera) {
  96597. return;
  96598. }
  96599. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  96600. var bottom = minimumWorld.y;
  96601. var top = maximumWorld.y;
  96602. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  96603. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  96604. if (focusOnOriginXZ) {
  96605. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  96606. }
  96607. else {
  96608. var centerWorld = minimumWorld.add(radiusWorld);
  96609. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  96610. }
  96611. if (!this._vectorTransition) {
  96612. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  96613. }
  96614. this._betaIsAnimating = true;
  96615. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  96616. if (animatable) {
  96617. this._animatables.push(animatable);
  96618. }
  96619. // sets the radius and lower radius bounds
  96620. // Small delta ensures camera is not always at lower zoom limit.
  96621. var radius = 0;
  96622. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  96623. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96624. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  96625. radius = position;
  96626. }
  96627. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96628. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  96629. if (this._attachedCamera.lowerRadiusLimit === null) {
  96630. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  96631. }
  96632. }
  96633. // Set sensibilities
  96634. var extend = maximumWorld.subtract(minimumWorld).length();
  96635. this._attachedCamera.panningSensibility = 5000 / extend;
  96636. this._attachedCamera.wheelPrecision = 100 / radius;
  96637. // transition to new radius
  96638. if (!this._radiusTransition) {
  96639. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96640. }
  96641. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  96642. _this.stopAllAnimations();
  96643. if (onAnimationEnd) {
  96644. onAnimationEnd();
  96645. }
  96646. if (_this._attachedCamera) {
  96647. _this._attachedCamera.storeState();
  96648. }
  96649. });
  96650. if (animatable) {
  96651. this._animatables.push(animatable);
  96652. }
  96653. };
  96654. /**
  96655. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  96656. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  96657. * frustum width.
  96658. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  96659. * to fully enclose the mesh in the viewing frustum.
  96660. */
  96661. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  96662. var size = maximumWorld.subtract(minimumWorld);
  96663. var boxVectorGlobalDiagonal = size.length();
  96664. var frustumSlope = this._getFrustumSlope();
  96665. // Formula for setting distance
  96666. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  96667. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  96668. // Horizon distance
  96669. var radius = radiusWithoutFraming * this._radiusScale;
  96670. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  96671. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  96672. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  96673. var camera = this._attachedCamera;
  96674. if (!camera) {
  96675. return 0;
  96676. }
  96677. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96678. // Don't exceed the requested limit
  96679. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  96680. }
  96681. // Don't exceed the upper radius limit
  96682. if (camera.upperRadiusLimit) {
  96683. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  96684. }
  96685. return distance;
  96686. };
  96687. /**
  96688. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  96689. * is automatically returned to its default position (expected to be above ground plane).
  96690. */
  96691. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  96692. var _this = this;
  96693. if (this._elevationReturnTime < 0) {
  96694. return;
  96695. }
  96696. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  96697. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  96698. var limitBeta = Math.PI * 0.5;
  96699. // Bring the camera back up if below the ground plane
  96700. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  96701. this._betaIsAnimating = true;
  96702. //Transition to new position
  96703. this.stopAllAnimations();
  96704. if (!this._betaTransition) {
  96705. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96706. }
  96707. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  96708. _this._clearAnimationLocks();
  96709. _this.stopAllAnimations();
  96710. });
  96711. if (animatabe) {
  96712. this._animatables.push(animatabe);
  96713. }
  96714. }
  96715. };
  96716. /**
  96717. * Returns the frustum slope based on the canvas ratio and camera FOV
  96718. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  96719. */
  96720. FramingBehavior.prototype._getFrustumSlope = function () {
  96721. // Calculate the viewport ratio
  96722. // Aspect Ratio is Height/Width.
  96723. var camera = this._attachedCamera;
  96724. if (!camera) {
  96725. return BABYLON.Vector2.Zero();
  96726. }
  96727. var engine = camera.getScene().getEngine();
  96728. var aspectRatio = engine.getAspectRatio(camera);
  96729. // Camera FOV is the vertical field of view (top-bottom) in radians.
  96730. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  96731. var frustumSlopeY = Math.tan(camera.fov / 2);
  96732. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  96733. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  96734. // along the forward vector.
  96735. var frustumSlopeX = frustumSlopeY * aspectRatio;
  96736. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  96737. };
  96738. /**
  96739. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  96740. */
  96741. FramingBehavior.prototype._clearAnimationLocks = function () {
  96742. this._betaIsAnimating = false;
  96743. };
  96744. /**
  96745. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  96746. */
  96747. FramingBehavior.prototype._applyUserInteraction = function () {
  96748. if (this.isUserIsMoving) {
  96749. this._lastInteractionTime = BABYLON.Tools.Now;
  96750. this.stopAllAnimations();
  96751. this._clearAnimationLocks();
  96752. }
  96753. };
  96754. /**
  96755. * Stops and removes all animations that have been applied to the camera
  96756. */
  96757. FramingBehavior.prototype.stopAllAnimations = function () {
  96758. if (this._attachedCamera) {
  96759. this._attachedCamera.animations = [];
  96760. }
  96761. while (this._animatables.length) {
  96762. if (this._animatables[0]) {
  96763. this._animatables[0].onAnimationEnd = null;
  96764. this._animatables[0].stop();
  96765. }
  96766. this._animatables.shift();
  96767. }
  96768. };
  96769. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  96770. /**
  96771. * Gets a value indicating if the user is moving the camera
  96772. */
  96773. get: function () {
  96774. if (!this._attachedCamera) {
  96775. return false;
  96776. }
  96777. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  96778. this._attachedCamera.inertialBetaOffset !== 0 ||
  96779. this._attachedCamera.inertialRadiusOffset !== 0 ||
  96780. this._attachedCamera.inertialPanningX !== 0 ||
  96781. this._attachedCamera.inertialPanningY !== 0 ||
  96782. this._isPointerDown;
  96783. },
  96784. enumerable: true,
  96785. configurable: true
  96786. });
  96787. /**
  96788. * The easing function used by animations
  96789. */
  96790. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  96791. /**
  96792. * The easing mode used by animations
  96793. */
  96794. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  96795. // Statics
  96796. /**
  96797. * The camera can move all the way towards the mesh.
  96798. */
  96799. FramingBehavior.IgnoreBoundsSizeMode = 0;
  96800. /**
  96801. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  96802. */
  96803. FramingBehavior.FitFrustumSidesMode = 1;
  96804. return FramingBehavior;
  96805. }());
  96806. BABYLON.FramingBehavior = FramingBehavior;
  96807. })(BABYLON || (BABYLON = {}));
  96808. //# sourceMappingURL=babylon.framingBehavior.js.map
  96809. var BABYLON;
  96810. (function (BABYLON) {
  96811. /**
  96812. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  96813. */
  96814. var BouncingBehavior = /** @class */ (function () {
  96815. function BouncingBehavior() {
  96816. /**
  96817. * The duration of the animation, in milliseconds
  96818. */
  96819. this.transitionDuration = 450;
  96820. /**
  96821. * Length of the distance animated by the transition when lower radius is reached
  96822. */
  96823. this.lowerRadiusTransitionRange = 2;
  96824. /**
  96825. * Length of the distance animated by the transition when upper radius is reached
  96826. */
  96827. this.upperRadiusTransitionRange = -2;
  96828. this._autoTransitionRange = false;
  96829. // Animations
  96830. this._radiusIsAnimating = false;
  96831. this._radiusBounceTransition = null;
  96832. this._animatables = new Array();
  96833. }
  96834. Object.defineProperty(BouncingBehavior.prototype, "name", {
  96835. get: function () {
  96836. return "Bouncing";
  96837. },
  96838. enumerable: true,
  96839. configurable: true
  96840. });
  96841. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  96842. /**
  96843. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96844. */
  96845. get: function () {
  96846. return this._autoTransitionRange;
  96847. },
  96848. /**
  96849. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96850. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  96851. */
  96852. set: function (value) {
  96853. var _this = this;
  96854. if (this._autoTransitionRange === value) {
  96855. return;
  96856. }
  96857. this._autoTransitionRange = value;
  96858. var camera = this._attachedCamera;
  96859. if (!camera) {
  96860. return;
  96861. }
  96862. if (value) {
  96863. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96864. if (!mesh) {
  96865. return;
  96866. }
  96867. mesh.computeWorldMatrix(true);
  96868. var diagonal = mesh.getBoundingInfo().diagonalLength;
  96869. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  96870. _this.upperRadiusTransitionRange = diagonal * 0.05;
  96871. });
  96872. }
  96873. else if (this._onMeshTargetChangedObserver) {
  96874. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96875. }
  96876. },
  96877. enumerable: true,
  96878. configurable: true
  96879. });
  96880. BouncingBehavior.prototype.init = function () {
  96881. // Do notihng
  96882. };
  96883. BouncingBehavior.prototype.attach = function (camera) {
  96884. var _this = this;
  96885. this._attachedCamera = camera;
  96886. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96887. if (!_this._attachedCamera) {
  96888. return;
  96889. }
  96890. // Add the bounce animation to the lower radius limit
  96891. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  96892. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  96893. }
  96894. // Add the bounce animation to the upper radius limit
  96895. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  96896. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  96897. }
  96898. });
  96899. };
  96900. BouncingBehavior.prototype.detach = function () {
  96901. if (!this._attachedCamera) {
  96902. return;
  96903. }
  96904. if (this._onAfterCheckInputsObserver) {
  96905. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96906. }
  96907. if (this._onMeshTargetChangedObserver) {
  96908. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96909. }
  96910. this._attachedCamera = null;
  96911. };
  96912. /**
  96913. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  96914. * @param radiusLimit The limit to check against.
  96915. * @return Bool to indicate if at limit.
  96916. */
  96917. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  96918. if (!this._attachedCamera) {
  96919. return false;
  96920. }
  96921. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  96922. return true;
  96923. }
  96924. return false;
  96925. };
  96926. /**
  96927. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  96928. * @param radiusDelta The delta by which to animate to. Can be negative.
  96929. */
  96930. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  96931. var _this = this;
  96932. if (!this._attachedCamera) {
  96933. return;
  96934. }
  96935. if (!this._radiusBounceTransition) {
  96936. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  96937. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  96938. }
  96939. // Prevent zoom until bounce has completed
  96940. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  96941. this._attachedCamera.wheelPrecision = Infinity;
  96942. this._attachedCamera.inertialRadiusOffset = 0;
  96943. // Animate to the radius limit
  96944. this.stopAllAnimations();
  96945. this._radiusIsAnimating = true;
  96946. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  96947. if (animatable) {
  96948. this._animatables.push(animatable);
  96949. }
  96950. };
  96951. /**
  96952. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  96953. */
  96954. BouncingBehavior.prototype._clearAnimationLocks = function () {
  96955. this._radiusIsAnimating = false;
  96956. if (this._attachedCamera) {
  96957. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  96958. }
  96959. };
  96960. /**
  96961. * Stops and removes all animations that have been applied to the camera
  96962. */
  96963. BouncingBehavior.prototype.stopAllAnimations = function () {
  96964. if (this._attachedCamera) {
  96965. this._attachedCamera.animations = [];
  96966. }
  96967. while (this._animatables.length) {
  96968. this._animatables[0].onAnimationEnd = null;
  96969. this._animatables[0].stop();
  96970. this._animatables.shift();
  96971. }
  96972. };
  96973. /**
  96974. * The easing function used by animations
  96975. */
  96976. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  96977. /**
  96978. * The easing mode used by animations
  96979. */
  96980. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  96981. return BouncingBehavior;
  96982. }());
  96983. BABYLON.BouncingBehavior = BouncingBehavior;
  96984. })(BABYLON || (BABYLON = {}));
  96985. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  96986. var BABYLON;
  96987. (function (BABYLON) {
  96988. var AutoRotationBehavior = /** @class */ (function () {
  96989. function AutoRotationBehavior() {
  96990. this._zoomStopsAnimation = false;
  96991. this._idleRotationSpeed = 0.05;
  96992. this._idleRotationWaitTime = 2000;
  96993. this._idleRotationSpinupTime = 2000;
  96994. this._isPointerDown = false;
  96995. this._lastFrameTime = null;
  96996. this._lastInteractionTime = -Infinity;
  96997. this._cameraRotationSpeed = 0;
  96998. this._lastFrameRadius = 0;
  96999. }
  97000. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  97001. get: function () {
  97002. return "AutoRotation";
  97003. },
  97004. enumerable: true,
  97005. configurable: true
  97006. });
  97007. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  97008. /**
  97009. * Gets the flag that indicates if user zooming should stop animation.
  97010. */
  97011. get: function () {
  97012. return this._zoomStopsAnimation;
  97013. },
  97014. /**
  97015. * Sets the flag that indicates if user zooming should stop animation.
  97016. */
  97017. set: function (flag) {
  97018. this._zoomStopsAnimation = flag;
  97019. },
  97020. enumerable: true,
  97021. configurable: true
  97022. });
  97023. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  97024. /**
  97025. * Gets the default speed at which the camera rotates around the model.
  97026. */
  97027. get: function () {
  97028. return this._idleRotationSpeed;
  97029. },
  97030. /**
  97031. * Sets the default speed at which the camera rotates around the model.
  97032. */
  97033. set: function (speed) {
  97034. this._idleRotationSpeed = speed;
  97035. },
  97036. enumerable: true,
  97037. configurable: true
  97038. });
  97039. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  97040. /**
  97041. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  97042. */
  97043. get: function () {
  97044. return this._idleRotationWaitTime;
  97045. },
  97046. /**
  97047. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  97048. */
  97049. set: function (time) {
  97050. this._idleRotationWaitTime = time;
  97051. },
  97052. enumerable: true,
  97053. configurable: true
  97054. });
  97055. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  97056. /**
  97057. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97058. */
  97059. get: function () {
  97060. return this._idleRotationSpinupTime;
  97061. },
  97062. /**
  97063. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  97064. */
  97065. set: function (time) {
  97066. this._idleRotationSpinupTime = time;
  97067. },
  97068. enumerable: true,
  97069. configurable: true
  97070. });
  97071. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  97072. /**
  97073. * Gets a value indicating if the camera is currently rotating because of this behavior
  97074. */
  97075. get: function () {
  97076. return Math.abs(this._cameraRotationSpeed) > 0;
  97077. },
  97078. enumerable: true,
  97079. configurable: true
  97080. });
  97081. AutoRotationBehavior.prototype.init = function () {
  97082. // Do notihng
  97083. };
  97084. AutoRotationBehavior.prototype.attach = function (camera) {
  97085. var _this = this;
  97086. this._attachedCamera = camera;
  97087. var scene = this._attachedCamera.getScene();
  97088. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  97089. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97090. _this._isPointerDown = true;
  97091. return;
  97092. }
  97093. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  97094. _this._isPointerDown = false;
  97095. }
  97096. });
  97097. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  97098. var now = BABYLON.Tools.Now;
  97099. var dt = 0;
  97100. if (_this._lastFrameTime != null) {
  97101. dt = now - _this._lastFrameTime;
  97102. }
  97103. _this._lastFrameTime = now;
  97104. // Stop the animation if there is user interaction and the animation should stop for this interaction
  97105. _this._applyUserInteraction();
  97106. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  97107. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  97108. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  97109. // Step camera rotation by rotation speed
  97110. if (_this._attachedCamera) {
  97111. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  97112. }
  97113. });
  97114. };
  97115. AutoRotationBehavior.prototype.detach = function () {
  97116. if (!this._attachedCamera) {
  97117. return;
  97118. }
  97119. var scene = this._attachedCamera.getScene();
  97120. if (this._onPrePointerObservableObserver) {
  97121. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  97122. }
  97123. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  97124. this._attachedCamera = null;
  97125. };
  97126. /**
  97127. * Returns true if user is scrolling.
  97128. * @return true if user is scrolling.
  97129. */
  97130. AutoRotationBehavior.prototype._userIsZooming = function () {
  97131. if (!this._attachedCamera) {
  97132. return false;
  97133. }
  97134. return this._attachedCamera.inertialRadiusOffset !== 0;
  97135. };
  97136. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  97137. if (!this._attachedCamera) {
  97138. return false;
  97139. }
  97140. var zoomHasHitLimit = false;
  97141. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  97142. zoomHasHitLimit = true;
  97143. }
  97144. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  97145. this._lastFrameRadius = this._attachedCamera.radius;
  97146. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  97147. };
  97148. /**
  97149. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  97150. */
  97151. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  97152. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  97153. this._lastInteractionTime = BABYLON.Tools.Now;
  97154. }
  97155. };
  97156. // Tools
  97157. AutoRotationBehavior.prototype._userIsMoving = function () {
  97158. if (!this._attachedCamera) {
  97159. return false;
  97160. }
  97161. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  97162. this._attachedCamera.inertialBetaOffset !== 0 ||
  97163. this._attachedCamera.inertialRadiusOffset !== 0 ||
  97164. this._attachedCamera.inertialPanningX !== 0 ||
  97165. this._attachedCamera.inertialPanningY !== 0 ||
  97166. this._isPointerDown;
  97167. };
  97168. return AutoRotationBehavior;
  97169. }());
  97170. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  97171. })(BABYLON || (BABYLON = {}));
  97172. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  97173. var BABYLON;
  97174. (function (BABYLON) {
  97175. var NullEngineOptions = /** @class */ (function () {
  97176. function NullEngineOptions() {
  97177. this.renderWidth = 512;
  97178. this.renderHeight = 256;
  97179. this.textureSize = 512;
  97180. this.deterministicLockstep = false;
  97181. this.lockstepMaxSteps = 4;
  97182. }
  97183. return NullEngineOptions;
  97184. }());
  97185. BABYLON.NullEngineOptions = NullEngineOptions;
  97186. /**
  97187. * The null engine class provides support for headless version of babylon.js.
  97188. * This can be used in server side scenario or for testing purposes
  97189. */
  97190. var NullEngine = /** @class */ (function (_super) {
  97191. __extends(NullEngine, _super);
  97192. function NullEngine(options) {
  97193. if (options === void 0) { options = new NullEngineOptions(); }
  97194. var _this = _super.call(this, null) || this;
  97195. if (options.deterministicLockstep === undefined) {
  97196. options.deterministicLockstep = false;
  97197. }
  97198. if (options.lockstepMaxSteps === undefined) {
  97199. options.lockstepMaxSteps = 4;
  97200. }
  97201. _this._options = options;
  97202. // Init caps
  97203. // We consider we are on a webgl1 capable device
  97204. _this._caps = new BABYLON.EngineCapabilities();
  97205. _this._caps.maxTexturesImageUnits = 16;
  97206. _this._caps.maxVertexTextureImageUnits = 16;
  97207. _this._caps.maxTextureSize = 512;
  97208. _this._caps.maxCubemapTextureSize = 512;
  97209. _this._caps.maxRenderTextureSize = 512;
  97210. _this._caps.maxVertexAttribs = 16;
  97211. _this._caps.maxVaryingVectors = 16;
  97212. _this._caps.maxFragmentUniformVectors = 16;
  97213. _this._caps.maxVertexUniformVectors = 16;
  97214. // Extensions
  97215. _this._caps.standardDerivatives = false;
  97216. _this._caps.astc = null;
  97217. _this._caps.s3tc = null;
  97218. _this._caps.pvrtc = null;
  97219. _this._caps.etc1 = null;
  97220. _this._caps.etc2 = null;
  97221. _this._caps.textureAnisotropicFilterExtension = null;
  97222. _this._caps.maxAnisotropy = 0;
  97223. _this._caps.uintIndices = false;
  97224. _this._caps.fragmentDepthSupported = false;
  97225. _this._caps.highPrecisionShaderSupported = true;
  97226. _this._caps.colorBufferFloat = false;
  97227. _this._caps.textureFloat = false;
  97228. _this._caps.textureFloatLinearFiltering = false;
  97229. _this._caps.textureFloatRender = false;
  97230. _this._caps.textureHalfFloat = false;
  97231. _this._caps.textureHalfFloatLinearFiltering = false;
  97232. _this._caps.textureHalfFloatRender = false;
  97233. _this._caps.textureLOD = false;
  97234. _this._caps.drawBuffersExtension = false;
  97235. _this._caps.depthTextureExtension = false;
  97236. _this._caps.vertexArrayObject = false;
  97237. _this._caps.instancedArrays = false;
  97238. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  97239. // Wrappers
  97240. if (typeof URL === "undefined") {
  97241. URL = {
  97242. createObjectURL: function () { },
  97243. revokeObjectURL: function () { }
  97244. };
  97245. }
  97246. if (typeof Blob === "undefined") {
  97247. Blob = function () { };
  97248. }
  97249. return _this;
  97250. }
  97251. NullEngine.prototype.isDeterministicLockStep = function () {
  97252. return this._options.deterministicLockstep;
  97253. };
  97254. NullEngine.prototype.getLockstepMaxSteps = function () {
  97255. return this._options.lockstepMaxSteps;
  97256. };
  97257. NullEngine.prototype.getHardwareScalingLevel = function () {
  97258. return 1.0;
  97259. };
  97260. NullEngine.prototype.createVertexBuffer = function (vertices) {
  97261. return {
  97262. capacity: 0,
  97263. references: 1,
  97264. is32Bits: false
  97265. };
  97266. };
  97267. NullEngine.prototype.createIndexBuffer = function (indices) {
  97268. return {
  97269. capacity: 0,
  97270. references: 1,
  97271. is32Bits: false
  97272. };
  97273. };
  97274. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  97275. if (stencil === void 0) { stencil = false; }
  97276. };
  97277. NullEngine.prototype.getRenderWidth = function (useScreen) {
  97278. if (useScreen === void 0) { useScreen = false; }
  97279. if (!useScreen && this._currentRenderTarget) {
  97280. return this._currentRenderTarget.width;
  97281. }
  97282. return this._options.renderWidth;
  97283. };
  97284. NullEngine.prototype.getRenderHeight = function (useScreen) {
  97285. if (useScreen === void 0) { useScreen = false; }
  97286. if (!useScreen && this._currentRenderTarget) {
  97287. return this._currentRenderTarget.height;
  97288. }
  97289. return this._options.renderHeight;
  97290. };
  97291. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  97292. this._cachedViewport = viewport;
  97293. };
  97294. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  97295. return {
  97296. transformFeedback: null,
  97297. __SPECTOR_rebuildProgram: null
  97298. };
  97299. };
  97300. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  97301. return [];
  97302. };
  97303. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  97304. return [];
  97305. };
  97306. NullEngine.prototype.bindSamplers = function (effect) {
  97307. this._currentEffect = null;
  97308. };
  97309. NullEngine.prototype.enableEffect = function (effect) {
  97310. this._currentEffect = effect;
  97311. if (effect.onBind) {
  97312. effect.onBind(effect);
  97313. }
  97314. effect.onBindObservable.notifyObservers(effect);
  97315. };
  97316. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  97317. if (zOffset === void 0) { zOffset = 0; }
  97318. if (reverseSide === void 0) { reverseSide = false; }
  97319. };
  97320. NullEngine.prototype.setIntArray = function (uniform, array) {
  97321. };
  97322. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  97323. };
  97324. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  97325. };
  97326. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  97327. };
  97328. NullEngine.prototype.setFloatArray = function (uniform, array) {
  97329. };
  97330. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  97331. };
  97332. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  97333. };
  97334. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  97335. };
  97336. NullEngine.prototype.setArray = function (uniform, array) {
  97337. };
  97338. NullEngine.prototype.setArray2 = function (uniform, array) {
  97339. };
  97340. NullEngine.prototype.setArray3 = function (uniform, array) {
  97341. };
  97342. NullEngine.prototype.setArray4 = function (uniform, array) {
  97343. };
  97344. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  97345. };
  97346. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  97347. };
  97348. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  97349. };
  97350. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  97351. };
  97352. NullEngine.prototype.setFloat = function (uniform, value) {
  97353. };
  97354. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  97355. };
  97356. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  97357. };
  97358. NullEngine.prototype.setBool = function (uniform, bool) {
  97359. };
  97360. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  97361. };
  97362. NullEngine.prototype.setColor3 = function (uniform, color3) {
  97363. };
  97364. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  97365. };
  97366. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  97367. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  97368. if (this._alphaMode === mode) {
  97369. return;
  97370. }
  97371. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  97372. if (!noDepthWriteChange) {
  97373. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  97374. }
  97375. this._alphaMode = mode;
  97376. };
  97377. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  97378. };
  97379. NullEngine.prototype.wipeCaches = function (bruteForce) {
  97380. if (this.preventCacheWipeBetweenFrames) {
  97381. return;
  97382. }
  97383. this.resetTextureCache();
  97384. this._currentEffect = null;
  97385. if (bruteForce) {
  97386. this._currentProgram = null;
  97387. this._stencilState.reset();
  97388. this._depthCullingState.reset();
  97389. this._alphaState.reset();
  97390. }
  97391. this._cachedVertexBuffers = null;
  97392. this._cachedIndexBuffer = null;
  97393. this._cachedEffectForVertexBuffers = null;
  97394. };
  97395. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  97396. };
  97397. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  97398. };
  97399. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  97400. };
  97401. NullEngine.prototype._createTexture = function () {
  97402. return {};
  97403. };
  97404. NullEngine.prototype._releaseTexture = function (texture) {
  97405. };
  97406. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  97407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97408. if (onLoad === void 0) { onLoad = null; }
  97409. if (onError === void 0) { onError = null; }
  97410. if (buffer === void 0) { buffer = null; }
  97411. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  97412. var url = String(urlArg);
  97413. texture.url = url;
  97414. texture.generateMipMaps = !noMipmap;
  97415. texture.samplingMode = samplingMode;
  97416. texture.invertY = invertY;
  97417. texture.baseWidth = this._options.textureSize;
  97418. texture.baseHeight = this._options.textureSize;
  97419. texture.width = this._options.textureSize;
  97420. texture.height = this._options.textureSize;
  97421. if (format) {
  97422. texture.format = format;
  97423. }
  97424. texture.isReady = true;
  97425. if (onLoad) {
  97426. onLoad();
  97427. }
  97428. this._internalTexturesCache.push(texture);
  97429. return texture;
  97430. };
  97431. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  97432. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  97433. if (options !== undefined && typeof options === "object") {
  97434. fullOptions.generateMipMaps = options.generateMipMaps;
  97435. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  97436. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  97437. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  97438. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  97439. }
  97440. else {
  97441. fullOptions.generateMipMaps = options;
  97442. fullOptions.generateDepthBuffer = true;
  97443. fullOptions.generateStencilBuffer = false;
  97444. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97445. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  97446. }
  97447. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  97448. var width = size.width || size;
  97449. var height = size.height || size;
  97450. texture._depthStencilBuffer = {};
  97451. texture._framebuffer = {};
  97452. texture.baseWidth = width;
  97453. texture.baseHeight = height;
  97454. texture.width = width;
  97455. texture.height = height;
  97456. texture.isReady = true;
  97457. texture.samples = 1;
  97458. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  97459. texture.samplingMode = fullOptions.samplingMode;
  97460. texture.type = fullOptions.type;
  97461. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  97462. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  97463. this._internalTexturesCache.push(texture);
  97464. return texture;
  97465. };
  97466. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  97467. texture.samplingMode = samplingMode;
  97468. };
  97469. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  97470. if (this._currentRenderTarget) {
  97471. this.unBindFramebuffer(this._currentRenderTarget);
  97472. }
  97473. this._currentRenderTarget = texture;
  97474. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  97475. if (this._cachedViewport && !forceFullscreenViewport) {
  97476. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  97477. }
  97478. };
  97479. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  97480. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  97481. this._currentRenderTarget = null;
  97482. if (onBeforeUnbind) {
  97483. if (texture._MSAAFramebuffer) {
  97484. this._currentFramebuffer = texture._framebuffer;
  97485. }
  97486. onBeforeUnbind();
  97487. }
  97488. this._currentFramebuffer = null;
  97489. };
  97490. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  97491. var vbo = {
  97492. capacity: 1,
  97493. references: 1,
  97494. is32Bits: false
  97495. };
  97496. return vbo;
  97497. };
  97498. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  97499. if (offset === void 0) { offset = 0; }
  97500. };
  97501. /**
  97502. * Updates a dynamic vertex buffer.
  97503. * @param vertexBuffer the vertex buffer to update
  97504. * @param data the data used to update the vertex buffer
  97505. * @param byteOffset the byte offset of the data (optional)
  97506. * @param byteLength the byte length of the data (optional)
  97507. */
  97508. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  97509. };
  97510. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  97511. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  97512. this._boundTexturesCache[this._activeChannel] = texture;
  97513. }
  97514. };
  97515. NullEngine.prototype._bindTexture = function (channel, texture) {
  97516. if (channel < 0) {
  97517. return;
  97518. }
  97519. this._bindTextureDirectly(0, texture);
  97520. };
  97521. NullEngine.prototype._releaseBuffer = function (buffer) {
  97522. buffer.references--;
  97523. if (buffer.references === 0) {
  97524. return true;
  97525. }
  97526. return false;
  97527. };
  97528. NullEngine.prototype.releaseEffects = function () {
  97529. };
  97530. return NullEngine;
  97531. }(BABYLON.Engine));
  97532. BABYLON.NullEngine = NullEngine;
  97533. })(BABYLON || (BABYLON = {}));
  97534. //# sourceMappingURL=babylon.nullEngine.js.map
  97535. var BABYLON;
  97536. (function (BABYLON) {
  97537. /**
  97538. * This class can be used to get instrumentation data from a Babylon engine
  97539. */
  97540. var EngineInstrumentation = /** @class */ (function () {
  97541. function EngineInstrumentation(engine) {
  97542. this.engine = engine;
  97543. this._captureGPUFrameTime = false;
  97544. this._gpuFrameTime = new BABYLON.PerfCounter();
  97545. this._captureShaderCompilationTime = false;
  97546. this._shaderCompilationTime = new BABYLON.PerfCounter();
  97547. // Observers
  97548. this._onBeginFrameObserver = null;
  97549. this._onEndFrameObserver = null;
  97550. this._onBeforeShaderCompilationObserver = null;
  97551. this._onAfterShaderCompilationObserver = null;
  97552. }
  97553. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  97554. // Properties
  97555. /**
  97556. * Gets the perf counter used for GPU frame time
  97557. */
  97558. get: function () {
  97559. return this._gpuFrameTime;
  97560. },
  97561. enumerable: true,
  97562. configurable: true
  97563. });
  97564. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  97565. /**
  97566. * Gets the GPU frame time capture status
  97567. */
  97568. get: function () {
  97569. return this._captureGPUFrameTime;
  97570. },
  97571. /**
  97572. * Enable or disable the GPU frame time capture
  97573. */
  97574. set: function (value) {
  97575. var _this = this;
  97576. if (value === this._captureGPUFrameTime) {
  97577. return;
  97578. }
  97579. this._captureGPUFrameTime = value;
  97580. if (value) {
  97581. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  97582. if (!_this._gpuFrameTimeToken) {
  97583. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  97584. }
  97585. });
  97586. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  97587. if (!_this._gpuFrameTimeToken) {
  97588. return;
  97589. }
  97590. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  97591. if (time > -1) {
  97592. _this._gpuFrameTimeToken = null;
  97593. _this._gpuFrameTime.fetchNewFrame();
  97594. _this._gpuFrameTime.addCount(time, true);
  97595. }
  97596. });
  97597. }
  97598. else {
  97599. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97600. this._onBeginFrameObserver = null;
  97601. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97602. this._onEndFrameObserver = null;
  97603. }
  97604. },
  97605. enumerable: true,
  97606. configurable: true
  97607. });
  97608. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  97609. /**
  97610. * Gets the perf counter used for shader compilation time
  97611. */
  97612. get: function () {
  97613. return this._shaderCompilationTime;
  97614. },
  97615. enumerable: true,
  97616. configurable: true
  97617. });
  97618. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  97619. /**
  97620. * Gets the shader compilation time capture status
  97621. */
  97622. get: function () {
  97623. return this._captureShaderCompilationTime;
  97624. },
  97625. /**
  97626. * Enable or disable the shader compilation time capture
  97627. */
  97628. set: function (value) {
  97629. var _this = this;
  97630. if (value === this._captureShaderCompilationTime) {
  97631. return;
  97632. }
  97633. this._captureShaderCompilationTime = value;
  97634. if (value) {
  97635. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  97636. _this._shaderCompilationTime.fetchNewFrame();
  97637. _this._shaderCompilationTime.beginMonitoring();
  97638. });
  97639. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  97640. _this._shaderCompilationTime.endMonitoring();
  97641. });
  97642. }
  97643. else {
  97644. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97645. this._onBeforeShaderCompilationObserver = null;
  97646. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97647. this._onAfterShaderCompilationObserver = null;
  97648. }
  97649. },
  97650. enumerable: true,
  97651. configurable: true
  97652. });
  97653. EngineInstrumentation.prototype.dispose = function () {
  97654. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97655. this._onBeginFrameObserver = null;
  97656. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97657. this._onEndFrameObserver = null;
  97658. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97659. this._onBeforeShaderCompilationObserver = null;
  97660. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97661. this._onAfterShaderCompilationObserver = null;
  97662. this.engine = null;
  97663. };
  97664. return EngineInstrumentation;
  97665. }());
  97666. BABYLON.EngineInstrumentation = EngineInstrumentation;
  97667. })(BABYLON || (BABYLON = {}));
  97668. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  97669. var BABYLON;
  97670. (function (BABYLON) {
  97671. /**
  97672. * This class can be used to get instrumentation data from a Babylon engine
  97673. */
  97674. var SceneInstrumentation = /** @class */ (function () {
  97675. function SceneInstrumentation(scene) {
  97676. var _this = this;
  97677. this.scene = scene;
  97678. this._captureActiveMeshesEvaluationTime = false;
  97679. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  97680. this._captureRenderTargetsRenderTime = false;
  97681. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  97682. this._captureFrameTime = false;
  97683. this._frameTime = new BABYLON.PerfCounter();
  97684. this._captureRenderTime = false;
  97685. this._renderTime = new BABYLON.PerfCounter();
  97686. this._captureInterFrameTime = false;
  97687. this._interFrameTime = new BABYLON.PerfCounter();
  97688. this._captureParticlesRenderTime = false;
  97689. this._particlesRenderTime = new BABYLON.PerfCounter();
  97690. this._captureSpritesRenderTime = false;
  97691. this._spritesRenderTime = new BABYLON.PerfCounter();
  97692. this._capturePhysicsTime = false;
  97693. this._physicsTime = new BABYLON.PerfCounter();
  97694. this._captureAnimationsTime = false;
  97695. this._animationsTime = new BABYLON.PerfCounter();
  97696. // Observers
  97697. this._onBeforeActiveMeshesEvaluationObserver = null;
  97698. this._onAfterActiveMeshesEvaluationObserver = null;
  97699. this._onBeforeRenderTargetsRenderObserver = null;
  97700. this._onAfterRenderTargetsRenderObserver = null;
  97701. this._onAfterRenderObserver = null;
  97702. this._onBeforeDrawPhaseObserver = null;
  97703. this._onAfterDrawPhaseObserver = null;
  97704. this._onBeforeAnimationsObserver = null;
  97705. this._onBeforeParticlesRenderingObserver = null;
  97706. this._onAfterParticlesRenderingObserver = null;
  97707. this._onBeforeSpritesRenderingObserver = null;
  97708. this._onAfterSpritesRenderingObserver = null;
  97709. this._onBeforePhysicsObserver = null;
  97710. this._onAfterPhysicsObserver = null;
  97711. this._onAfterAnimationsObserver = null;
  97712. // Before render
  97713. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  97714. if (_this._captureActiveMeshesEvaluationTime) {
  97715. _this._activeMeshesEvaluationTime.fetchNewFrame();
  97716. }
  97717. if (_this._captureRenderTargetsRenderTime) {
  97718. _this._renderTargetsRenderTime.fetchNewFrame();
  97719. }
  97720. if (_this._captureFrameTime) {
  97721. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  97722. _this._frameTime.beginMonitoring();
  97723. }
  97724. if (_this._captureInterFrameTime) {
  97725. _this._interFrameTime.endMonitoring();
  97726. }
  97727. if (_this._captureParticlesRenderTime) {
  97728. _this._particlesRenderTime.fetchNewFrame();
  97729. }
  97730. if (_this._captureSpritesRenderTime) {
  97731. _this._spritesRenderTime.fetchNewFrame();
  97732. }
  97733. if (_this._captureAnimationsTime) {
  97734. _this._animationsTime.beginMonitoring();
  97735. }
  97736. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  97737. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  97738. });
  97739. // After render
  97740. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  97741. if (_this._captureFrameTime) {
  97742. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  97743. _this._frameTime.endMonitoring();
  97744. }
  97745. if (_this._captureRenderTime) {
  97746. _this._renderTime.endMonitoring(false);
  97747. }
  97748. if (_this._captureInterFrameTime) {
  97749. _this._interFrameTime.beginMonitoring();
  97750. }
  97751. });
  97752. }
  97753. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  97754. // Properties
  97755. /**
  97756. * Gets the perf counter used for active meshes evaluation time
  97757. */
  97758. get: function () {
  97759. return this._activeMeshesEvaluationTime;
  97760. },
  97761. enumerable: true,
  97762. configurable: true
  97763. });
  97764. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  97765. /**
  97766. * Gets the active meshes evaluation time capture status
  97767. */
  97768. get: function () {
  97769. return this._captureActiveMeshesEvaluationTime;
  97770. },
  97771. /**
  97772. * Enable or disable the active meshes evaluation time capture
  97773. */
  97774. set: function (value) {
  97775. var _this = this;
  97776. if (value === this._captureActiveMeshesEvaluationTime) {
  97777. return;
  97778. }
  97779. this._captureActiveMeshesEvaluationTime = value;
  97780. if (value) {
  97781. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  97782. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  97783. _this._activeMeshesEvaluationTime.beginMonitoring();
  97784. });
  97785. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  97786. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  97787. _this._activeMeshesEvaluationTime.endMonitoring();
  97788. });
  97789. }
  97790. else {
  97791. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  97792. this._onBeforeActiveMeshesEvaluationObserver = null;
  97793. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  97794. this._onAfterActiveMeshesEvaluationObserver = null;
  97795. }
  97796. },
  97797. enumerable: true,
  97798. configurable: true
  97799. });
  97800. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  97801. /**
  97802. * Gets the perf counter used for render targets render time
  97803. */
  97804. get: function () {
  97805. return this._renderTargetsRenderTime;
  97806. },
  97807. enumerable: true,
  97808. configurable: true
  97809. });
  97810. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  97811. /**
  97812. * Gets the render targets render time capture status
  97813. */
  97814. get: function () {
  97815. return this._captureRenderTargetsRenderTime;
  97816. },
  97817. /**
  97818. * Enable or disable the render targets render time capture
  97819. */
  97820. set: function (value) {
  97821. var _this = this;
  97822. if (value === this._captureRenderTargetsRenderTime) {
  97823. return;
  97824. }
  97825. this._captureRenderTargetsRenderTime = value;
  97826. if (value) {
  97827. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  97828. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  97829. _this._renderTargetsRenderTime.beginMonitoring();
  97830. });
  97831. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  97832. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  97833. _this._renderTargetsRenderTime.endMonitoring(false);
  97834. });
  97835. }
  97836. else {
  97837. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  97838. this._onBeforeRenderTargetsRenderObserver = null;
  97839. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  97840. this._onAfterRenderTargetsRenderObserver = null;
  97841. }
  97842. },
  97843. enumerable: true,
  97844. configurable: true
  97845. });
  97846. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  97847. /**
  97848. * Gets the perf counter used for particles render time
  97849. */
  97850. get: function () {
  97851. return this._particlesRenderTime;
  97852. },
  97853. enumerable: true,
  97854. configurable: true
  97855. });
  97856. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  97857. /**
  97858. * Gets the particles render time capture status
  97859. */
  97860. get: function () {
  97861. return this._captureParticlesRenderTime;
  97862. },
  97863. /**
  97864. * Enable or disable the particles render time capture
  97865. */
  97866. set: function (value) {
  97867. var _this = this;
  97868. if (value === this._captureParticlesRenderTime) {
  97869. return;
  97870. }
  97871. this._captureParticlesRenderTime = value;
  97872. if (value) {
  97873. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  97874. BABYLON.Tools.StartPerformanceCounter("Particles");
  97875. _this._particlesRenderTime.beginMonitoring();
  97876. });
  97877. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  97878. BABYLON.Tools.EndPerformanceCounter("Particles");
  97879. _this._particlesRenderTime.endMonitoring(false);
  97880. });
  97881. }
  97882. else {
  97883. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  97884. this._onBeforeParticlesRenderingObserver = null;
  97885. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  97886. this._onAfterParticlesRenderingObserver = null;
  97887. }
  97888. },
  97889. enumerable: true,
  97890. configurable: true
  97891. });
  97892. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  97893. /**
  97894. * Gets the perf counter used for sprites render time
  97895. */
  97896. get: function () {
  97897. return this._spritesRenderTime;
  97898. },
  97899. enumerable: true,
  97900. configurable: true
  97901. });
  97902. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  97903. /**
  97904. * Gets the sprites render time capture status
  97905. */
  97906. get: function () {
  97907. return this._captureSpritesRenderTime;
  97908. },
  97909. /**
  97910. * Enable or disable the sprites render time capture
  97911. */
  97912. set: function (value) {
  97913. var _this = this;
  97914. if (value === this._captureSpritesRenderTime) {
  97915. return;
  97916. }
  97917. this._captureSpritesRenderTime = value;
  97918. if (value) {
  97919. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  97920. BABYLON.Tools.StartPerformanceCounter("Sprites");
  97921. _this._spritesRenderTime.beginMonitoring();
  97922. });
  97923. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  97924. BABYLON.Tools.EndPerformanceCounter("Sprites");
  97925. _this._spritesRenderTime.endMonitoring(false);
  97926. });
  97927. }
  97928. else {
  97929. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  97930. this._onBeforeSpritesRenderingObserver = null;
  97931. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  97932. this._onAfterSpritesRenderingObserver = null;
  97933. }
  97934. },
  97935. enumerable: true,
  97936. configurable: true
  97937. });
  97938. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  97939. /**
  97940. * Gets the perf counter used for physics time
  97941. */
  97942. get: function () {
  97943. return this._physicsTime;
  97944. },
  97945. enumerable: true,
  97946. configurable: true
  97947. });
  97948. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  97949. /**
  97950. * Gets the physics time capture status
  97951. */
  97952. get: function () {
  97953. return this._capturePhysicsTime;
  97954. },
  97955. /**
  97956. * Enable or disable the physics time capture
  97957. */
  97958. set: function (value) {
  97959. var _this = this;
  97960. if (value === this._capturePhysicsTime) {
  97961. return;
  97962. }
  97963. this._capturePhysicsTime = value;
  97964. if (value) {
  97965. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  97966. BABYLON.Tools.StartPerformanceCounter("Physics");
  97967. _this._physicsTime.beginMonitoring();
  97968. });
  97969. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  97970. BABYLON.Tools.EndPerformanceCounter("Physics");
  97971. _this._physicsTime.endMonitoring();
  97972. });
  97973. }
  97974. else {
  97975. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  97976. this._onBeforePhysicsObserver = null;
  97977. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  97978. this._onAfterPhysicsObserver = null;
  97979. }
  97980. },
  97981. enumerable: true,
  97982. configurable: true
  97983. });
  97984. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  97985. /**
  97986. * Gets the perf counter used for animations time
  97987. */
  97988. get: function () {
  97989. return this._animationsTime;
  97990. },
  97991. enumerable: true,
  97992. configurable: true
  97993. });
  97994. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  97995. /**
  97996. * Gets the animations time capture status
  97997. */
  97998. get: function () {
  97999. return this._captureAnimationsTime;
  98000. },
  98001. /**
  98002. * Enable or disable the animations time capture
  98003. */
  98004. set: function (value) {
  98005. var _this = this;
  98006. if (value === this._captureAnimationsTime) {
  98007. return;
  98008. }
  98009. this._captureAnimationsTime = value;
  98010. if (value) {
  98011. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  98012. _this._animationsTime.endMonitoring();
  98013. });
  98014. }
  98015. else {
  98016. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98017. this._onAfterAnimationsObserver = null;
  98018. }
  98019. },
  98020. enumerable: true,
  98021. configurable: true
  98022. });
  98023. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  98024. /**
  98025. * Gets the perf counter used for frame time capture
  98026. */
  98027. get: function () {
  98028. return this._frameTime;
  98029. },
  98030. enumerable: true,
  98031. configurable: true
  98032. });
  98033. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  98034. /**
  98035. * Gets the frame time capture status
  98036. */
  98037. get: function () {
  98038. return this._captureFrameTime;
  98039. },
  98040. /**
  98041. * Enable or disable the frame time capture
  98042. */
  98043. set: function (value) {
  98044. this._captureFrameTime = value;
  98045. },
  98046. enumerable: true,
  98047. configurable: true
  98048. });
  98049. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  98050. /**
  98051. * Gets the perf counter used for inter-frames time capture
  98052. */
  98053. get: function () {
  98054. return this._interFrameTime;
  98055. },
  98056. enumerable: true,
  98057. configurable: true
  98058. });
  98059. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  98060. /**
  98061. * Gets the inter-frames time capture status
  98062. */
  98063. get: function () {
  98064. return this._captureInterFrameTime;
  98065. },
  98066. /**
  98067. * Enable or disable the inter-frames time capture
  98068. */
  98069. set: function (value) {
  98070. this._captureInterFrameTime = value;
  98071. },
  98072. enumerable: true,
  98073. configurable: true
  98074. });
  98075. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  98076. /**
  98077. * Gets the perf counter used for render time capture
  98078. */
  98079. get: function () {
  98080. return this._renderTime;
  98081. },
  98082. enumerable: true,
  98083. configurable: true
  98084. });
  98085. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  98086. /**
  98087. * Gets the render time capture status
  98088. */
  98089. get: function () {
  98090. return this._captureRenderTime;
  98091. },
  98092. /**
  98093. * Enable or disable the render time capture
  98094. */
  98095. set: function (value) {
  98096. var _this = this;
  98097. if (value === this._captureRenderTime) {
  98098. return;
  98099. }
  98100. this._captureRenderTime = value;
  98101. if (value) {
  98102. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  98103. _this._renderTime.beginMonitoring();
  98104. BABYLON.Tools.StartPerformanceCounter("Main render");
  98105. });
  98106. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  98107. _this._renderTime.endMonitoring(false);
  98108. BABYLON.Tools.EndPerformanceCounter("Main render");
  98109. });
  98110. }
  98111. else {
  98112. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98113. this._onBeforeDrawPhaseObserver = null;
  98114. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98115. this._onAfterDrawPhaseObserver = null;
  98116. }
  98117. },
  98118. enumerable: true,
  98119. configurable: true
  98120. });
  98121. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  98122. /**
  98123. * Gets the perf counter used for draw calls
  98124. */
  98125. get: function () {
  98126. return this.scene.getEngine()._drawCalls;
  98127. },
  98128. enumerable: true,
  98129. configurable: true
  98130. });
  98131. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  98132. /**
  98133. * Gets the perf counter used for texture collisions
  98134. */
  98135. get: function () {
  98136. return this.scene.getEngine()._textureCollisions;
  98137. },
  98138. enumerable: true,
  98139. configurable: true
  98140. });
  98141. SceneInstrumentation.prototype.dispose = function () {
  98142. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98143. this._onAfterRenderObserver = null;
  98144. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  98145. this._onBeforeActiveMeshesEvaluationObserver = null;
  98146. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  98147. this._onAfterActiveMeshesEvaluationObserver = null;
  98148. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  98149. this._onBeforeRenderTargetsRenderObserver = null;
  98150. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  98151. this._onAfterRenderTargetsRenderObserver = null;
  98152. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  98153. this._onBeforeAnimationsObserver = null;
  98154. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  98155. this._onBeforeParticlesRenderingObserver = null;
  98156. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  98157. this._onAfterParticlesRenderingObserver = null;
  98158. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  98159. this._onBeforeSpritesRenderingObserver = null;
  98160. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  98161. this._onAfterSpritesRenderingObserver = null;
  98162. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  98163. this._onBeforeDrawPhaseObserver = null;
  98164. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  98165. this._onAfterDrawPhaseObserver = null;
  98166. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  98167. this._onBeforePhysicsObserver = null;
  98168. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  98169. this._onAfterPhysicsObserver = null;
  98170. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  98171. this._onAfterAnimationsObserver = null;
  98172. this.scene = null;
  98173. };
  98174. return SceneInstrumentation;
  98175. }());
  98176. BABYLON.SceneInstrumentation = SceneInstrumentation;
  98177. })(BABYLON || (BABYLON = {}));
  98178. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  98179. var BABYLON;
  98180. (function (BABYLON) {
  98181. /**
  98182. * @hidden
  98183. **/
  98184. var _TimeToken = /** @class */ (function () {
  98185. function _TimeToken() {
  98186. this._timeElapsedQueryEnded = false;
  98187. }
  98188. return _TimeToken;
  98189. }());
  98190. BABYLON._TimeToken = _TimeToken;
  98191. })(BABYLON || (BABYLON = {}));
  98192. //# sourceMappingURL=babylon.timeToken.js.map
  98193. var BABYLON;
  98194. (function (BABYLON) {
  98195. /**
  98196. * Background material defines definition.
  98197. * @hidden Mainly internal Use
  98198. */
  98199. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  98200. __extends(BackgroundMaterialDefines, _super);
  98201. /**
  98202. * Constructor of the defines.
  98203. */
  98204. function BackgroundMaterialDefines() {
  98205. var _this = _super.call(this) || this;
  98206. /**
  98207. * True if the diffuse texture is in use.
  98208. */
  98209. _this.DIFFUSE = false;
  98210. /**
  98211. * The direct UV channel to use.
  98212. */
  98213. _this.DIFFUSEDIRECTUV = 0;
  98214. /**
  98215. * True if the diffuse texture is in gamma space.
  98216. */
  98217. _this.GAMMADIFFUSE = false;
  98218. /**
  98219. * True if the diffuse texture has opacity in the alpha channel.
  98220. */
  98221. _this.DIFFUSEHASALPHA = false;
  98222. /**
  98223. * True if you want the material to fade to transparent at grazing angle.
  98224. */
  98225. _this.OPACITYFRESNEL = false;
  98226. /**
  98227. * True if an extra blur needs to be added in the reflection.
  98228. */
  98229. _this.REFLECTIONBLUR = false;
  98230. /**
  98231. * True if you want the material to fade to reflection at grazing angle.
  98232. */
  98233. _this.REFLECTIONFRESNEL = false;
  98234. /**
  98235. * True if you want the material to falloff as far as you move away from the scene center.
  98236. */
  98237. _this.REFLECTIONFALLOFF = false;
  98238. /**
  98239. * False if the current Webgl implementation does not support the texture lod extension.
  98240. */
  98241. _this.TEXTURELODSUPPORT = false;
  98242. /**
  98243. * True to ensure the data are premultiplied.
  98244. */
  98245. _this.PREMULTIPLYALPHA = false;
  98246. /**
  98247. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  98248. */
  98249. _this.USERGBCOLOR = false;
  98250. /**
  98251. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  98252. * stays aligned with the desired configuration.
  98253. */
  98254. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  98255. /**
  98256. * True to add noise in order to reduce the banding effect.
  98257. */
  98258. _this.NOISE = false;
  98259. /**
  98260. * is the reflection texture in BGR color scheme?
  98261. * Mainly used to solve a bug in ios10 video tag
  98262. */
  98263. _this.REFLECTIONBGR = false;
  98264. _this.IMAGEPROCESSING = false;
  98265. _this.VIGNETTE = false;
  98266. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  98267. _this.VIGNETTEBLENDMODEOPAQUE = false;
  98268. _this.TONEMAPPING = false;
  98269. _this.CONTRAST = false;
  98270. _this.COLORCURVES = false;
  98271. _this.COLORGRADING = false;
  98272. _this.COLORGRADING3D = false;
  98273. _this.SAMPLER3DGREENDEPTH = false;
  98274. _this.SAMPLER3DBGRMAP = false;
  98275. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  98276. _this.EXPOSURE = false;
  98277. // Reflection.
  98278. _this.REFLECTION = false;
  98279. _this.REFLECTIONMAP_3D = false;
  98280. _this.REFLECTIONMAP_SPHERICAL = false;
  98281. _this.REFLECTIONMAP_PLANAR = false;
  98282. _this.REFLECTIONMAP_CUBIC = false;
  98283. _this.REFLECTIONMAP_PROJECTION = false;
  98284. _this.REFLECTIONMAP_SKYBOX = false;
  98285. _this.REFLECTIONMAP_EXPLICIT = false;
  98286. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98287. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98288. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98289. _this.INVERTCUBICMAP = false;
  98290. _this.REFLECTIONMAP_OPPOSITEZ = false;
  98291. _this.LODINREFLECTIONALPHA = false;
  98292. _this.GAMMAREFLECTION = false;
  98293. _this.RGBDREFLECTION = false;
  98294. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  98295. // Default BJS.
  98296. _this.MAINUV1 = false;
  98297. _this.MAINUV2 = false;
  98298. _this.UV1 = false;
  98299. _this.UV2 = false;
  98300. _this.CLIPPLANE = false;
  98301. _this.POINTSIZE = false;
  98302. _this.FOG = false;
  98303. _this.NORMAL = false;
  98304. _this.NUM_BONE_INFLUENCERS = 0;
  98305. _this.BonesPerMesh = 0;
  98306. _this.INSTANCES = false;
  98307. _this.SHADOWFLOAT = false;
  98308. _this.rebuild();
  98309. return _this;
  98310. }
  98311. return BackgroundMaterialDefines;
  98312. }(BABYLON.MaterialDefines));
  98313. /**
  98314. * Background material used to create an efficient environement around your scene.
  98315. */
  98316. var BackgroundMaterial = /** @class */ (function (_super) {
  98317. __extends(BackgroundMaterial, _super);
  98318. /**
  98319. * Instantiates a Background Material in the given scene
  98320. * @param name The friendly name of the material
  98321. * @param scene The scene to add the material to
  98322. */
  98323. function BackgroundMaterial(name, scene) {
  98324. var _this = _super.call(this, name, scene) || this;
  98325. /**
  98326. * Key light Color (multiply against the environement texture)
  98327. */
  98328. _this.primaryColor = BABYLON.Color3.White();
  98329. _this._primaryColorShadowLevel = 0;
  98330. _this._primaryColorHighlightLevel = 0;
  98331. /**
  98332. * Reflection Texture used in the material.
  98333. * Should be author in a specific way for the best result (refer to the documentation).
  98334. */
  98335. _this.reflectionTexture = null;
  98336. /**
  98337. * Reflection Texture level of blur.
  98338. *
  98339. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  98340. * texture twice.
  98341. */
  98342. _this.reflectionBlur = 0;
  98343. /**
  98344. * Diffuse Texture used in the material.
  98345. * Should be author in a specific way for the best result (refer to the documentation).
  98346. */
  98347. _this.diffuseTexture = null;
  98348. _this._shadowLights = null;
  98349. /**
  98350. * Specify the list of lights casting shadow on the material.
  98351. * All scene shadow lights will be included if null.
  98352. */
  98353. _this.shadowLights = null;
  98354. /**
  98355. * Helps adjusting the shadow to a softer level if required.
  98356. * 0 means black shadows and 1 means no shadows.
  98357. */
  98358. _this.shadowLevel = 0;
  98359. /**
  98360. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  98361. * It is usually zero but might be interesting to modify according to your setup.
  98362. */
  98363. _this.sceneCenter = BABYLON.Vector3.Zero();
  98364. /**
  98365. * This helps specifying that the material is falling off to the sky box at grazing angle.
  98366. * This helps ensuring a nice transition when the camera goes under the ground.
  98367. */
  98368. _this.opacityFresnel = true;
  98369. /**
  98370. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  98371. * This helps adding a mirror texture on the ground.
  98372. */
  98373. _this.reflectionFresnel = false;
  98374. /**
  98375. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  98376. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  98377. */
  98378. _this.reflectionFalloffDistance = 0.0;
  98379. /**
  98380. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  98381. */
  98382. _this.reflectionAmount = 1.0;
  98383. /**
  98384. * This specifies the weight of the reflection at grazing angle.
  98385. */
  98386. _this.reflectionReflectance0 = 0.05;
  98387. /**
  98388. * This specifies the weight of the reflection at a perpendicular point of view.
  98389. */
  98390. _this.reflectionReflectance90 = 0.5;
  98391. /**
  98392. * Helps to directly use the maps channels instead of their level.
  98393. */
  98394. _this.useRGBColor = true;
  98395. /**
  98396. * This helps reducing the banding effect that could occur on the background.
  98397. */
  98398. _this.enableNoise = false;
  98399. _this._fovMultiplier = 1.0;
  98400. /**
  98401. * Enable the FOV adjustment feature controlled by fovMultiplier.
  98402. */
  98403. _this.useEquirectangularFOV = false;
  98404. _this._maxSimultaneousLights = 4;
  98405. /**
  98406. * Number of Simultaneous lights allowed on the material.
  98407. */
  98408. _this.maxSimultaneousLights = 4;
  98409. /**
  98410. * Keep track of the image processing observer to allow dispose and replace.
  98411. */
  98412. _this._imageProcessingObserver = null;
  98413. /**
  98414. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  98415. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  98416. */
  98417. _this.switchToBGR = false;
  98418. // Temp values kept as cache in the material.
  98419. _this._renderTargets = new BABYLON.SmartArray(16);
  98420. _this._reflectionControls = BABYLON.Vector4.Zero();
  98421. _this._white = BABYLON.Color3.White();
  98422. _this._primaryShadowColor = BABYLON.Color3.Black();
  98423. _this._primaryHighlightColor = BABYLON.Color3.Black();
  98424. // Setup the default processing configuration to the scene.
  98425. _this._attachImageProcessingConfiguration(null);
  98426. _this.getRenderTargetTextures = function () {
  98427. _this._renderTargets.reset();
  98428. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  98429. _this._renderTargets.push(_this._diffuseTexture);
  98430. }
  98431. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  98432. _this._renderTargets.push(_this._reflectionTexture);
  98433. }
  98434. return _this._renderTargets;
  98435. };
  98436. return _this;
  98437. }
  98438. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  98439. /**
  98440. * Experimental Internal Use Only.
  98441. *
  98442. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  98443. * This acts as a helper to set the primary color to a more "human friendly" value.
  98444. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  98445. * output color as close as possible from the chosen value.
  98446. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  98447. * part of lighting setup.)
  98448. */
  98449. get: function () {
  98450. return this.__perceptualColor;
  98451. },
  98452. set: function (value) {
  98453. this.__perceptualColor = value;
  98454. this._computePrimaryColorFromPerceptualColor();
  98455. this._markAllSubMeshesAsLightsDirty();
  98456. },
  98457. enumerable: true,
  98458. configurable: true
  98459. });
  98460. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  98461. /**
  98462. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  98463. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  98464. */
  98465. get: function () {
  98466. return this._primaryColorShadowLevel;
  98467. },
  98468. set: function (value) {
  98469. this._primaryColorShadowLevel = value;
  98470. this._computePrimaryColors();
  98471. this._markAllSubMeshesAsLightsDirty();
  98472. },
  98473. enumerable: true,
  98474. configurable: true
  98475. });
  98476. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  98477. /**
  98478. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  98479. * The primary color is used at the level chosen to define what the white area would look.
  98480. */
  98481. get: function () {
  98482. return this._primaryColorHighlightLevel;
  98483. },
  98484. set: function (value) {
  98485. this._primaryColorHighlightLevel = value;
  98486. this._computePrimaryColors();
  98487. this._markAllSubMeshesAsLightsDirty();
  98488. },
  98489. enumerable: true,
  98490. configurable: true
  98491. });
  98492. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  98493. /**
  98494. * Sets the reflection reflectance fresnel values according to the default standard
  98495. * empirically know to work well :-)
  98496. */
  98497. set: function (value) {
  98498. var reflectionWeight = value;
  98499. if (reflectionWeight < 0.5) {
  98500. reflectionWeight = reflectionWeight * 2.0;
  98501. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  98502. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  98503. }
  98504. else {
  98505. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  98506. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  98507. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  98508. }
  98509. },
  98510. enumerable: true,
  98511. configurable: true
  98512. });
  98513. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  98514. /**
  98515. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98516. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  98517. * Recommended to be keep at 1.0 except for special cases.
  98518. */
  98519. get: function () {
  98520. return this._fovMultiplier;
  98521. },
  98522. set: function (value) {
  98523. if (isNaN(value)) {
  98524. value = 1.0;
  98525. }
  98526. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  98527. },
  98528. enumerable: true,
  98529. configurable: true
  98530. });
  98531. /**
  98532. * Attaches a new image processing configuration to the PBR Material.
  98533. * @param configuration (if null the scene configuration will be use)
  98534. */
  98535. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  98536. var _this = this;
  98537. if (configuration === this._imageProcessingConfiguration) {
  98538. return;
  98539. }
  98540. // Detaches observer.
  98541. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98542. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98543. }
  98544. // Pick the scene configuration if needed.
  98545. if (!configuration) {
  98546. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  98547. }
  98548. else {
  98549. this._imageProcessingConfiguration = configuration;
  98550. }
  98551. // Attaches observer.
  98552. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  98553. _this._computePrimaryColorFromPerceptualColor();
  98554. _this._markAllSubMeshesAsImageProcessingDirty();
  98555. });
  98556. };
  98557. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  98558. /**
  98559. * Gets the image processing configuration used either in this material.
  98560. */
  98561. get: function () {
  98562. return this._imageProcessingConfiguration;
  98563. },
  98564. /**
  98565. * Sets the Default image processing configuration used either in the this material.
  98566. *
  98567. * If sets to null, the scene one is in use.
  98568. */
  98569. set: function (value) {
  98570. this._attachImageProcessingConfiguration(value);
  98571. // Ensure the effect will be rebuilt.
  98572. this._markAllSubMeshesAsTexturesDirty();
  98573. },
  98574. enumerable: true,
  98575. configurable: true
  98576. });
  98577. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  98578. /**
  98579. * Gets wether the color curves effect is enabled.
  98580. */
  98581. get: function () {
  98582. return this.imageProcessingConfiguration.colorCurvesEnabled;
  98583. },
  98584. /**
  98585. * Sets wether the color curves effect is enabled.
  98586. */
  98587. set: function (value) {
  98588. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  98589. },
  98590. enumerable: true,
  98591. configurable: true
  98592. });
  98593. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  98594. /**
  98595. * Gets wether the color grading effect is enabled.
  98596. */
  98597. get: function () {
  98598. return this.imageProcessingConfiguration.colorGradingEnabled;
  98599. },
  98600. /**
  98601. * Gets wether the color grading effect is enabled.
  98602. */
  98603. set: function (value) {
  98604. this.imageProcessingConfiguration.colorGradingEnabled = value;
  98605. },
  98606. enumerable: true,
  98607. configurable: true
  98608. });
  98609. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  98610. /**
  98611. * Gets wether tonemapping is enabled or not.
  98612. */
  98613. get: function () {
  98614. return this._imageProcessingConfiguration.toneMappingEnabled;
  98615. },
  98616. /**
  98617. * Sets wether tonemapping is enabled or not
  98618. */
  98619. set: function (value) {
  98620. this._imageProcessingConfiguration.toneMappingEnabled = value;
  98621. },
  98622. enumerable: true,
  98623. configurable: true
  98624. });
  98625. ;
  98626. ;
  98627. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  98628. /**
  98629. * The camera exposure used on this material.
  98630. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98631. * This corresponds to a photographic exposure.
  98632. */
  98633. get: function () {
  98634. return this._imageProcessingConfiguration.exposure;
  98635. },
  98636. /**
  98637. * The camera exposure used on this material.
  98638. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  98639. * This corresponds to a photographic exposure.
  98640. */
  98641. set: function (value) {
  98642. this._imageProcessingConfiguration.exposure = value;
  98643. },
  98644. enumerable: true,
  98645. configurable: true
  98646. });
  98647. ;
  98648. ;
  98649. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  98650. /**
  98651. * Gets The camera contrast used on this material.
  98652. */
  98653. get: function () {
  98654. return this._imageProcessingConfiguration.contrast;
  98655. },
  98656. /**
  98657. * Sets The camera contrast used on this material.
  98658. */
  98659. set: function (value) {
  98660. this._imageProcessingConfiguration.contrast = value;
  98661. },
  98662. enumerable: true,
  98663. configurable: true
  98664. });
  98665. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  98666. /**
  98667. * Gets the Color Grading 2D Lookup Texture.
  98668. */
  98669. get: function () {
  98670. return this._imageProcessingConfiguration.colorGradingTexture;
  98671. },
  98672. /**
  98673. * Sets the Color Grading 2D Lookup Texture.
  98674. */
  98675. set: function (value) {
  98676. this.imageProcessingConfiguration.colorGradingTexture = value;
  98677. },
  98678. enumerable: true,
  98679. configurable: true
  98680. });
  98681. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  98682. /**
  98683. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98684. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98685. * 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;
  98686. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98687. */
  98688. get: function () {
  98689. return this.imageProcessingConfiguration.colorCurves;
  98690. },
  98691. /**
  98692. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98693. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98694. * 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;
  98695. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98696. */
  98697. set: function (value) {
  98698. this.imageProcessingConfiguration.colorCurves = value;
  98699. },
  98700. enumerable: true,
  98701. configurable: true
  98702. });
  98703. /**
  98704. * The entire material has been created in order to prevent overdraw.
  98705. * @returns false
  98706. */
  98707. BackgroundMaterial.prototype.needAlphaTesting = function () {
  98708. return true;
  98709. };
  98710. /**
  98711. * The entire material has been created in order to prevent overdraw.
  98712. * @returns true if blending is enable
  98713. */
  98714. BackgroundMaterial.prototype.needAlphaBlending = function () {
  98715. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  98716. };
  98717. /**
  98718. * Checks wether the material is ready to be rendered for a given mesh.
  98719. * @param mesh The mesh to render
  98720. * @param subMesh The submesh to check against
  98721. * @param useInstances Specify wether or not the material is used with instances
  98722. * @returns true if all the dependencies are ready (Textures, Effects...)
  98723. */
  98724. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  98725. var _this = this;
  98726. if (useInstances === void 0) { useInstances = false; }
  98727. if (subMesh.effect && this.isFrozen) {
  98728. if (this._wasPreviouslyReady) {
  98729. return true;
  98730. }
  98731. }
  98732. if (!subMesh._materialDefines) {
  98733. subMesh._materialDefines = new BackgroundMaterialDefines();
  98734. }
  98735. var scene = this.getScene();
  98736. var defines = subMesh._materialDefines;
  98737. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  98738. if (defines._renderId === scene.getRenderId()) {
  98739. return true;
  98740. }
  98741. }
  98742. var engine = scene.getEngine();
  98743. // Lights
  98744. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  98745. defines._needNormals = true;
  98746. // Textures
  98747. if (defines._areTexturesDirty) {
  98748. defines._needUVs = false;
  98749. if (scene.texturesEnabled) {
  98750. if (scene.getEngine().getCaps().textureLOD) {
  98751. defines.TEXTURELODSUPPORT = true;
  98752. }
  98753. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98754. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  98755. return false;
  98756. }
  98757. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  98758. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  98759. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  98760. defines.OPACITYFRESNEL = this._opacityFresnel;
  98761. }
  98762. else {
  98763. defines.DIFFUSE = false;
  98764. defines.DIFFUSEHASALPHA = false;
  98765. defines.GAMMADIFFUSE = false;
  98766. defines.OPACITYFRESNEL = false;
  98767. }
  98768. var reflectionTexture = this._reflectionTexture;
  98769. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98770. if (!reflectionTexture.isReadyOrNotBlocking()) {
  98771. return false;
  98772. }
  98773. defines.REFLECTION = true;
  98774. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  98775. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  98776. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  98777. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  98778. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  98779. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  98780. defines.REFLECTIONBGR = this.switchToBGR;
  98781. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  98782. defines.INVERTCUBICMAP = true;
  98783. }
  98784. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  98785. switch (reflectionTexture.coordinatesMode) {
  98786. case BABYLON.Texture.EXPLICIT_MODE:
  98787. defines.REFLECTIONMAP_EXPLICIT = true;
  98788. break;
  98789. case BABYLON.Texture.PLANAR_MODE:
  98790. defines.REFLECTIONMAP_PLANAR = true;
  98791. break;
  98792. case BABYLON.Texture.PROJECTION_MODE:
  98793. defines.REFLECTIONMAP_PROJECTION = true;
  98794. break;
  98795. case BABYLON.Texture.SKYBOX_MODE:
  98796. defines.REFLECTIONMAP_SKYBOX = true;
  98797. break;
  98798. case BABYLON.Texture.SPHERICAL_MODE:
  98799. defines.REFLECTIONMAP_SPHERICAL = true;
  98800. break;
  98801. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  98802. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  98803. break;
  98804. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  98805. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  98806. break;
  98807. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  98808. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  98809. break;
  98810. case BABYLON.Texture.CUBIC_MODE:
  98811. case BABYLON.Texture.INVCUBIC_MODE:
  98812. default:
  98813. defines.REFLECTIONMAP_CUBIC = true;
  98814. break;
  98815. }
  98816. if (this.reflectionFresnel) {
  98817. defines.REFLECTIONFRESNEL = true;
  98818. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  98819. this._reflectionControls.x = this.reflectionAmount;
  98820. this._reflectionControls.y = this.reflectionReflectance0;
  98821. this._reflectionControls.z = this.reflectionReflectance90;
  98822. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  98823. }
  98824. else {
  98825. defines.REFLECTIONFRESNEL = false;
  98826. defines.REFLECTIONFALLOFF = false;
  98827. }
  98828. }
  98829. else {
  98830. defines.REFLECTION = false;
  98831. defines.REFLECTIONFRESNEL = false;
  98832. defines.REFLECTIONFALLOFF = false;
  98833. defines.REFLECTIONBLUR = false;
  98834. defines.REFLECTIONMAP_3D = false;
  98835. defines.REFLECTIONMAP_SPHERICAL = false;
  98836. defines.REFLECTIONMAP_PLANAR = false;
  98837. defines.REFLECTIONMAP_CUBIC = false;
  98838. defines.REFLECTIONMAP_PROJECTION = false;
  98839. defines.REFLECTIONMAP_SKYBOX = false;
  98840. defines.REFLECTIONMAP_EXPLICIT = false;
  98841. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98842. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98843. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98844. defines.INVERTCUBICMAP = false;
  98845. defines.REFLECTIONMAP_OPPOSITEZ = false;
  98846. defines.LODINREFLECTIONALPHA = false;
  98847. defines.GAMMAREFLECTION = false;
  98848. defines.RGBDREFLECTION = false;
  98849. }
  98850. }
  98851. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  98852. defines.USERGBCOLOR = this._useRGBColor;
  98853. defines.NOISE = this._enableNoise;
  98854. }
  98855. if (defines._areLightsDirty) {
  98856. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  98857. }
  98858. if (defines._areImageProcessingDirty) {
  98859. if (!this._imageProcessingConfiguration.isReady()) {
  98860. return false;
  98861. }
  98862. this._imageProcessingConfiguration.prepareDefines(defines);
  98863. }
  98864. // Misc.
  98865. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  98866. // Values that need to be evaluated on every frame
  98867. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  98868. // Attribs
  98869. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  98870. if (mesh) {
  98871. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98872. mesh.createNormals(true);
  98873. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  98874. }
  98875. }
  98876. }
  98877. // Get correct effect
  98878. if (defines.isDirty) {
  98879. defines.markAsProcessed();
  98880. scene.resetCachedMaterial();
  98881. // Fallbacks
  98882. var fallbacks = new BABYLON.EffectFallbacks();
  98883. if (defines.FOG) {
  98884. fallbacks.addFallback(0, "FOG");
  98885. }
  98886. if (defines.POINTSIZE) {
  98887. fallbacks.addFallback(1, "POINTSIZE");
  98888. }
  98889. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  98890. if (defines.NUM_BONE_INFLUENCERS > 0) {
  98891. fallbacks.addCPUSkinningFallback(0, mesh);
  98892. }
  98893. //Attributes
  98894. var attribs = [BABYLON.VertexBuffer.PositionKind];
  98895. if (defines.NORMAL) {
  98896. attribs.push(BABYLON.VertexBuffer.NormalKind);
  98897. }
  98898. if (defines.UV1) {
  98899. attribs.push(BABYLON.VertexBuffer.UVKind);
  98900. }
  98901. if (defines.UV2) {
  98902. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98903. }
  98904. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  98905. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  98906. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  98907. "vFogInfos", "vFogColor", "pointSize",
  98908. "vClipPlane", "mBones",
  98909. "vPrimaryColor", "vPrimaryColorShadow",
  98910. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  98911. "shadowLevel", "alpha",
  98912. "vBackgroundCenter", "vReflectionControl",
  98913. "vDiffuseInfos", "diffuseMatrix",
  98914. ];
  98915. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  98916. var uniformBuffers = ["Material", "Scene"];
  98917. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  98918. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  98919. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  98920. uniformsNames: uniforms,
  98921. uniformBuffersNames: uniformBuffers,
  98922. samplers: samplers,
  98923. defines: defines,
  98924. maxSimultaneousLights: this._maxSimultaneousLights
  98925. });
  98926. var onCompiled = function (effect) {
  98927. if (_this.onCompiled) {
  98928. _this.onCompiled(effect);
  98929. }
  98930. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  98931. };
  98932. var join = defines.toString();
  98933. subMesh.setEffect(scene.getEngine().createEffect("background", {
  98934. attributes: attribs,
  98935. uniformsNames: uniforms,
  98936. uniformBuffersNames: uniformBuffers,
  98937. samplers: samplers,
  98938. defines: join,
  98939. fallbacks: fallbacks,
  98940. onCompiled: onCompiled,
  98941. onError: this.onError,
  98942. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  98943. }, engine), defines);
  98944. this.buildUniformLayout();
  98945. }
  98946. if (!subMesh.effect || !subMesh.effect.isReady()) {
  98947. return false;
  98948. }
  98949. defines._renderId = scene.getRenderId();
  98950. this._wasPreviouslyReady = true;
  98951. return true;
  98952. };
  98953. /**
  98954. * Compute the primary color according to the chosen perceptual color.
  98955. */
  98956. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  98957. if (!this.__perceptualColor) {
  98958. return;
  98959. }
  98960. this._primaryColor.copyFrom(this.__perceptualColor);
  98961. // Revert gamma space.
  98962. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  98963. // Revert image processing configuration.
  98964. if (this._imageProcessingConfiguration) {
  98965. // Revert Exposure.
  98966. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  98967. }
  98968. this._computePrimaryColors();
  98969. };
  98970. /**
  98971. * Compute the highlights and shadow colors according to their chosen levels.
  98972. */
  98973. BackgroundMaterial.prototype._computePrimaryColors = function () {
  98974. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  98975. return;
  98976. }
  98977. // Find the highlight color based on the configuration.
  98978. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  98979. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  98980. // Find the shadow color based on the configuration.
  98981. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  98982. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  98983. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  98984. };
  98985. /**
  98986. * Build the uniform buffer used in the material.
  98987. */
  98988. BackgroundMaterial.prototype.buildUniformLayout = function () {
  98989. // Order is important !
  98990. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  98991. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  98992. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  98993. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  98994. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  98995. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  98996. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  98997. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  98998. this._uniformBuffer.addUniform("pointSize", 1);
  98999. this._uniformBuffer.addUniform("shadowLevel", 1);
  99000. this._uniformBuffer.addUniform("alpha", 1);
  99001. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  99002. this._uniformBuffer.addUniform("vReflectionControl", 4);
  99003. this._uniformBuffer.create();
  99004. };
  99005. /**
  99006. * Unbind the material.
  99007. */
  99008. BackgroundMaterial.prototype.unbind = function () {
  99009. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  99010. this._uniformBuffer.setTexture("diffuseSampler", null);
  99011. }
  99012. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  99013. this._uniformBuffer.setTexture("reflectionSampler", null);
  99014. }
  99015. _super.prototype.unbind.call(this);
  99016. };
  99017. /**
  99018. * Bind only the world matrix to the material.
  99019. * @param world The world matrix to bind.
  99020. */
  99021. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  99022. this._activeEffect.setMatrix("world", world);
  99023. };
  99024. /**
  99025. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  99026. * @param world The world matrix to bind.
  99027. * @param subMesh The submesh to bind for.
  99028. */
  99029. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  99030. var scene = this.getScene();
  99031. var defines = subMesh._materialDefines;
  99032. if (!defines) {
  99033. return;
  99034. }
  99035. var effect = subMesh.effect;
  99036. if (!effect) {
  99037. return;
  99038. }
  99039. this._activeEffect = effect;
  99040. // Matrices
  99041. this.bindOnlyWorldMatrix(world);
  99042. // Bones
  99043. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  99044. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  99045. if (mustRebind) {
  99046. this._uniformBuffer.bindToEffect(effect, "Material");
  99047. this.bindViewProjection(effect);
  99048. var reflectionTexture = this._reflectionTexture;
  99049. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  99050. // Texture uniforms
  99051. if (scene.texturesEnabled) {
  99052. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99053. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  99054. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  99055. }
  99056. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99057. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  99058. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  99059. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  99060. }
  99061. }
  99062. if (this.shadowLevel > 0) {
  99063. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  99064. }
  99065. this._uniformBuffer.updateFloat("alpha", this.alpha);
  99066. // Point size
  99067. if (this.pointsCloud) {
  99068. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  99069. }
  99070. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  99071. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  99072. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  99073. }
  99074. else {
  99075. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  99076. }
  99077. }
  99078. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  99079. // Textures
  99080. if (scene.texturesEnabled) {
  99081. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  99082. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  99083. }
  99084. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  99085. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  99086. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99087. }
  99088. else if (!defines.REFLECTIONBLUR) {
  99089. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  99090. }
  99091. else {
  99092. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  99093. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  99094. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  99095. }
  99096. if (defines.REFLECTIONFRESNEL) {
  99097. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  99098. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  99099. }
  99100. }
  99101. }
  99102. // Clip plane
  99103. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  99104. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  99105. }
  99106. if (mustRebind || !this.isFrozen) {
  99107. if (scene.lightsEnabled) {
  99108. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  99109. }
  99110. // View
  99111. this.bindView(effect);
  99112. // Fog
  99113. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  99114. // image processing
  99115. this._imageProcessingConfiguration.bind(this._activeEffect);
  99116. }
  99117. this._uniformBuffer.update();
  99118. this._afterBind(mesh);
  99119. };
  99120. /**
  99121. * Dispose the material.
  99122. * @param forceDisposeEffect Force disposal of the associated effect.
  99123. * @param forceDisposeTextures Force disposal of the associated textures.
  99124. */
  99125. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  99126. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  99127. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  99128. if (forceDisposeTextures) {
  99129. if (this.diffuseTexture) {
  99130. this.diffuseTexture.dispose();
  99131. }
  99132. if (this.reflectionTexture) {
  99133. this.reflectionTexture.dispose();
  99134. }
  99135. }
  99136. this._renderTargets.dispose();
  99137. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  99138. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  99139. }
  99140. _super.prototype.dispose.call(this, forceDisposeEffect);
  99141. };
  99142. /**
  99143. * Clones the material.
  99144. * @param name The cloned name.
  99145. * @returns The cloned material.
  99146. */
  99147. BackgroundMaterial.prototype.clone = function (name) {
  99148. var _this = this;
  99149. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  99150. };
  99151. /**
  99152. * Serializes the current material to its JSON representation.
  99153. * @returns The JSON representation.
  99154. */
  99155. BackgroundMaterial.prototype.serialize = function () {
  99156. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99157. serializationObject.customType = "BABYLON.BackgroundMaterial";
  99158. return serializationObject;
  99159. };
  99160. /**
  99161. * Gets the class name of the material
  99162. * @returns "BackgroundMaterial"
  99163. */
  99164. BackgroundMaterial.prototype.getClassName = function () {
  99165. return "BackgroundMaterial";
  99166. };
  99167. /**
  99168. * Parse a JSON input to create back a background material.
  99169. * @param source The JSON data to parse
  99170. * @param scene The scene to create the parsed material in
  99171. * @param rootUrl The root url of the assets the material depends upon
  99172. * @returns the instantiated BackgroundMaterial.
  99173. */
  99174. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  99175. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  99176. };
  99177. /**
  99178. * Standard reflectance value at parallel view angle.
  99179. */
  99180. BackgroundMaterial.StandardReflectance0 = 0.05;
  99181. /**
  99182. * Standard reflectance value at grazing angle.
  99183. */
  99184. BackgroundMaterial.StandardReflectance90 = 0.5;
  99185. __decorate([
  99186. BABYLON.serializeAsColor3()
  99187. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  99188. __decorate([
  99189. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99190. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  99191. __decorate([
  99192. BABYLON.serializeAsColor3()
  99193. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  99194. __decorate([
  99195. BABYLON.serialize()
  99196. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  99197. __decorate([
  99198. BABYLON.serialize()
  99199. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  99200. __decorate([
  99201. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  99202. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  99203. __decorate([
  99204. BABYLON.serializeAsTexture()
  99205. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  99206. __decorate([
  99207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99208. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  99209. __decorate([
  99210. BABYLON.serialize()
  99211. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  99212. __decorate([
  99213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99214. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  99215. __decorate([
  99216. BABYLON.serializeAsTexture()
  99217. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  99218. __decorate([
  99219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99220. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  99221. __decorate([
  99222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99223. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  99224. __decorate([
  99225. BABYLON.serialize()
  99226. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  99227. __decorate([
  99228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99229. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  99230. __decorate([
  99231. BABYLON.serializeAsVector3()
  99232. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  99233. __decorate([
  99234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99235. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  99236. __decorate([
  99237. BABYLON.serialize()
  99238. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  99239. __decorate([
  99240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99241. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  99242. __decorate([
  99243. BABYLON.serialize()
  99244. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  99245. __decorate([
  99246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99247. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  99248. __decorate([
  99249. BABYLON.serialize()
  99250. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  99251. __decorate([
  99252. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99253. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  99254. __decorate([
  99255. BABYLON.serialize()
  99256. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  99257. __decorate([
  99258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99259. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  99260. __decorate([
  99261. BABYLON.serialize()
  99262. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  99263. __decorate([
  99264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99265. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  99266. __decorate([
  99267. BABYLON.serialize()
  99268. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  99269. __decorate([
  99270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99271. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  99272. __decorate([
  99273. BABYLON.serialize()
  99274. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  99275. __decorate([
  99276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99277. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  99278. __decorate([
  99279. BABYLON.serialize()
  99280. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  99281. __decorate([
  99282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99283. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  99284. __decorate([
  99285. BABYLON.serialize()
  99286. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  99287. __decorate([
  99288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  99289. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  99290. __decorate([
  99291. BABYLON.serializeAsImageProcessingConfiguration()
  99292. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  99293. return BackgroundMaterial;
  99294. }(BABYLON.PushMaterial));
  99295. BABYLON.BackgroundMaterial = BackgroundMaterial;
  99296. })(BABYLON || (BABYLON = {}));
  99297. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  99298. var __assign = (this && this.__assign) || Object.assign || function(t) {
  99299. for (var s, i = 1, n = arguments.length; i < n; i++) {
  99300. s = arguments[i];
  99301. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  99302. t[p] = s[p];
  99303. }
  99304. return t;
  99305. };
  99306. var BABYLON;
  99307. (function (BABYLON) {
  99308. /**
  99309. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  99310. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  99311. * It also helps with the default setup of your imageProcessing configuration.
  99312. */
  99313. var EnvironmentHelper = /** @class */ (function () {
  99314. /**
  99315. * constructor
  99316. * @param options
  99317. * @param scene The scene to add the material to
  99318. */
  99319. function EnvironmentHelper(options, scene) {
  99320. var _this = this;
  99321. this._errorHandler = function (message, exception) {
  99322. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  99323. };
  99324. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  99325. this._scene = scene;
  99326. this.onErrorObservable = new BABYLON.Observable();
  99327. this._setupBackground();
  99328. this._setupImageProcessing();
  99329. }
  99330. /**
  99331. * Creates the default options for the helper.
  99332. */
  99333. EnvironmentHelper._getDefaultOptions = function () {
  99334. return {
  99335. createGround: true,
  99336. groundSize: 15,
  99337. groundTexture: this._groundTextureCDNUrl,
  99338. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99339. groundOpacity: 0.9,
  99340. enableGroundShadow: true,
  99341. groundShadowLevel: 0.5,
  99342. enableGroundMirror: false,
  99343. groundMirrorSizeRatio: 0.3,
  99344. groundMirrorBlurKernel: 64,
  99345. groundMirrorAmount: 1,
  99346. groundMirrorFresnelWeight: 1,
  99347. groundMirrorFallOffDistance: 0,
  99348. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  99349. groundYBias: 0.00001,
  99350. createSkybox: true,
  99351. skyboxSize: 20,
  99352. skyboxTexture: this._skyboxTextureCDNUrl,
  99353. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  99354. backgroundYRotation: 0,
  99355. sizeAuto: true,
  99356. rootPosition: BABYLON.Vector3.Zero(),
  99357. setupImageProcessing: true,
  99358. environmentTexture: this._environmentTextureCDNUrl,
  99359. cameraExposure: 0.8,
  99360. cameraContrast: 1.2,
  99361. toneMappingEnabled: true,
  99362. };
  99363. };
  99364. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  99365. /**
  99366. * Gets the root mesh created by the helper.
  99367. */
  99368. get: function () {
  99369. return this._rootMesh;
  99370. },
  99371. enumerable: true,
  99372. configurable: true
  99373. });
  99374. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  99375. /**
  99376. * Gets the skybox created by the helper.
  99377. */
  99378. get: function () {
  99379. return this._skybox;
  99380. },
  99381. enumerable: true,
  99382. configurable: true
  99383. });
  99384. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  99385. /**
  99386. * Gets the skybox texture created by the helper.
  99387. */
  99388. get: function () {
  99389. return this._skyboxTexture;
  99390. },
  99391. enumerable: true,
  99392. configurable: true
  99393. });
  99394. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  99395. /**
  99396. * Gets the skybox material created by the helper.
  99397. */
  99398. get: function () {
  99399. return this._skyboxMaterial;
  99400. },
  99401. enumerable: true,
  99402. configurable: true
  99403. });
  99404. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  99405. /**
  99406. * Gets the ground mesh created by the helper.
  99407. */
  99408. get: function () {
  99409. return this._ground;
  99410. },
  99411. enumerable: true,
  99412. configurable: true
  99413. });
  99414. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  99415. /**
  99416. * Gets the ground texture created by the helper.
  99417. */
  99418. get: function () {
  99419. return this._groundTexture;
  99420. },
  99421. enumerable: true,
  99422. configurable: true
  99423. });
  99424. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  99425. /**
  99426. * Gets the ground mirror created by the helper.
  99427. */
  99428. get: function () {
  99429. return this._groundMirror;
  99430. },
  99431. enumerable: true,
  99432. configurable: true
  99433. });
  99434. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  99435. /**
  99436. * Gets the ground mirror render list to helps pushing the meshes
  99437. * you wish in the ground reflection.
  99438. */
  99439. get: function () {
  99440. if (this._groundMirror) {
  99441. return this._groundMirror.renderList;
  99442. }
  99443. return null;
  99444. },
  99445. enumerable: true,
  99446. configurable: true
  99447. });
  99448. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  99449. /**
  99450. * Gets the ground material created by the helper.
  99451. */
  99452. get: function () {
  99453. return this._groundMaterial;
  99454. },
  99455. enumerable: true,
  99456. configurable: true
  99457. });
  99458. /**
  99459. * Updates the background according to the new options
  99460. * @param options
  99461. */
  99462. EnvironmentHelper.prototype.updateOptions = function (options) {
  99463. var newOptions = __assign({}, this._options, options);
  99464. if (this._ground && !newOptions.createGround) {
  99465. this._ground.dispose();
  99466. this._ground = null;
  99467. }
  99468. if (this._groundMaterial && !newOptions.createGround) {
  99469. this._groundMaterial.dispose();
  99470. this._groundMaterial = null;
  99471. }
  99472. if (this._groundTexture) {
  99473. if (this._options.groundTexture != newOptions.groundTexture) {
  99474. this._groundTexture.dispose();
  99475. this._groundTexture = null;
  99476. }
  99477. }
  99478. if (this._skybox && !newOptions.createSkybox) {
  99479. this._skybox.dispose();
  99480. this._skybox = null;
  99481. }
  99482. if (this._skyboxMaterial && !newOptions.createSkybox) {
  99483. this._skyboxMaterial.dispose();
  99484. this._skyboxMaterial = null;
  99485. }
  99486. if (this._skyboxTexture) {
  99487. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  99488. this._skyboxTexture.dispose();
  99489. this._skyboxTexture = null;
  99490. }
  99491. }
  99492. if (this._groundMirror && !newOptions.enableGroundMirror) {
  99493. this._groundMirror.dispose();
  99494. this._groundMirror = null;
  99495. }
  99496. if (this._scene.environmentTexture) {
  99497. if (this._options.environmentTexture != newOptions.environmentTexture) {
  99498. this._scene.environmentTexture.dispose();
  99499. }
  99500. }
  99501. this._options = newOptions;
  99502. this._setupBackground();
  99503. this._setupImageProcessing();
  99504. };
  99505. /**
  99506. * Sets the primary color of all the available elements.
  99507. * @param color the main color to affect to the ground and the background
  99508. */
  99509. EnvironmentHelper.prototype.setMainColor = function (color) {
  99510. if (this.groundMaterial) {
  99511. this.groundMaterial.primaryColor = color;
  99512. }
  99513. if (this.skyboxMaterial) {
  99514. this.skyboxMaterial.primaryColor = color;
  99515. }
  99516. if (this.groundMirror) {
  99517. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  99518. }
  99519. };
  99520. /**
  99521. * Setup the image processing according to the specified options.
  99522. */
  99523. EnvironmentHelper.prototype._setupImageProcessing = function () {
  99524. if (this._options.setupImageProcessing) {
  99525. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  99526. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  99527. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  99528. this._setupEnvironmentTexture();
  99529. }
  99530. };
  99531. /**
  99532. * Setup the environment texture according to the specified options.
  99533. */
  99534. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  99535. if (this._scene.environmentTexture) {
  99536. return;
  99537. }
  99538. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  99539. this._scene.environmentTexture = this._options.environmentTexture;
  99540. return;
  99541. }
  99542. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  99543. this._scene.environmentTexture = environmentTexture;
  99544. };
  99545. /**
  99546. * Setup the background according to the specified options.
  99547. */
  99548. EnvironmentHelper.prototype._setupBackground = function () {
  99549. if (!this._rootMesh) {
  99550. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  99551. }
  99552. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  99553. var sceneSize = this._getSceneSize();
  99554. if (this._options.createGround) {
  99555. this._setupGround(sceneSize);
  99556. this._setupGroundMaterial();
  99557. this._setupGroundDiffuseTexture();
  99558. if (this._options.enableGroundMirror) {
  99559. this._setupGroundMirrorTexture(sceneSize);
  99560. }
  99561. this._setupMirrorInGroundMaterial();
  99562. }
  99563. if (this._options.createSkybox) {
  99564. this._setupSkybox(sceneSize);
  99565. this._setupSkyboxMaterial();
  99566. this._setupSkyboxReflectionTexture();
  99567. }
  99568. this._rootMesh.position.x = sceneSize.rootPosition.x;
  99569. this._rootMesh.position.z = sceneSize.rootPosition.z;
  99570. this._rootMesh.position.y = sceneSize.rootPosition.y;
  99571. };
  99572. /**
  99573. * Get the scene sizes according to the setup.
  99574. */
  99575. EnvironmentHelper.prototype._getSceneSize = function () {
  99576. var _this = this;
  99577. var groundSize = this._options.groundSize;
  99578. var skyboxSize = this._options.skyboxSize;
  99579. var rootPosition = this._options.rootPosition;
  99580. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  99581. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99582. }
  99583. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  99584. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  99585. });
  99586. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  99587. if (this._options.sizeAuto) {
  99588. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  99589. this._scene.activeCamera.upperRadiusLimit) {
  99590. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  99591. skyboxSize = groundSize;
  99592. }
  99593. var sceneDiagonalLenght = sceneDiagonal.length();
  99594. if (sceneDiagonalLenght > groundSize) {
  99595. groundSize = sceneDiagonalLenght * 2;
  99596. skyboxSize = groundSize;
  99597. }
  99598. // 10 % bigger.
  99599. groundSize *= 1.1;
  99600. skyboxSize *= 1.5;
  99601. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  99602. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  99603. }
  99604. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  99605. };
  99606. /**
  99607. * Setup the ground according to the specified options.
  99608. */
  99609. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  99610. var _this = this;
  99611. if (!this._ground) {
  99612. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  99613. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  99614. this._ground.parent = this._rootMesh;
  99615. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  99616. }
  99617. this._ground.receiveShadows = this._options.enableGroundShadow;
  99618. };
  99619. /**
  99620. * Setup the ground material according to the specified options.
  99621. */
  99622. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  99623. if (!this._groundMaterial) {
  99624. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  99625. }
  99626. this._groundMaterial.alpha = this._options.groundOpacity;
  99627. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  99628. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  99629. this._groundMaterial.primaryColor = this._options.groundColor;
  99630. this._groundMaterial.useRGBColor = false;
  99631. this._groundMaterial.enableNoise = true;
  99632. if (this._ground) {
  99633. this._ground.material = this._groundMaterial;
  99634. }
  99635. };
  99636. /**
  99637. * Setup the ground diffuse texture according to the specified options.
  99638. */
  99639. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  99640. if (!this._groundMaterial) {
  99641. return;
  99642. }
  99643. if (this._groundTexture) {
  99644. return;
  99645. }
  99646. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  99647. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  99648. return;
  99649. }
  99650. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99651. diffuseTexture.gammaSpace = false;
  99652. diffuseTexture.hasAlpha = true;
  99653. this._groundMaterial.diffuseTexture = diffuseTexture;
  99654. };
  99655. /**
  99656. * Setup the ground mirror texture according to the specified options.
  99657. */
  99658. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  99659. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99660. if (!this._groundMirror) {
  99661. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  99662. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  99663. this._groundMirror.anisotropicFilteringLevel = 1;
  99664. this._groundMirror.wrapU = wrapping;
  99665. this._groundMirror.wrapV = wrapping;
  99666. this._groundMirror.gammaSpace = false;
  99667. if (this._groundMirror.renderList) {
  99668. for (var i = 0; i < this._scene.meshes.length; i++) {
  99669. var mesh = this._scene.meshes[i];
  99670. if (mesh !== this._ground &&
  99671. mesh !== this._skybox &&
  99672. mesh !== this._rootMesh) {
  99673. this._groundMirror.renderList.push(mesh);
  99674. }
  99675. }
  99676. }
  99677. }
  99678. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  99679. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  99680. };
  99681. /**
  99682. * Setup the ground to receive the mirror texture.
  99683. */
  99684. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  99685. if (this._groundMaterial) {
  99686. this._groundMaterial.reflectionTexture = this._groundMirror;
  99687. this._groundMaterial.reflectionFresnel = true;
  99688. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  99689. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  99690. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  99691. }
  99692. };
  99693. /**
  99694. * Setup the skybox according to the specified options.
  99695. */
  99696. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  99697. var _this = this;
  99698. if (!this._skybox) {
  99699. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  99700. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  99701. }
  99702. this._skybox.parent = this._rootMesh;
  99703. };
  99704. /**
  99705. * Setup the skybox material according to the specified options.
  99706. */
  99707. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  99708. if (!this._skybox) {
  99709. return;
  99710. }
  99711. if (!this._skyboxMaterial) {
  99712. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  99713. }
  99714. this._skyboxMaterial.useRGBColor = false;
  99715. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  99716. this._skyboxMaterial.enableNoise = true;
  99717. this._skybox.material = this._skyboxMaterial;
  99718. };
  99719. /**
  99720. * Setup the skybox reflection texture according to the specified options.
  99721. */
  99722. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  99723. if (!this._skyboxMaterial) {
  99724. return;
  99725. }
  99726. if (this._skyboxTexture) {
  99727. return;
  99728. }
  99729. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  99730. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  99731. return;
  99732. }
  99733. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99734. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  99735. this._skyboxTexture.gammaSpace = false;
  99736. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  99737. };
  99738. /**
  99739. * Dispose all the elements created by the Helper.
  99740. */
  99741. EnvironmentHelper.prototype.dispose = function () {
  99742. if (this._groundMaterial) {
  99743. this._groundMaterial.dispose(true, true);
  99744. }
  99745. if (this._skyboxMaterial) {
  99746. this._skyboxMaterial.dispose(true, true);
  99747. }
  99748. this._rootMesh.dispose(false);
  99749. };
  99750. /**
  99751. * Default ground texture URL.
  99752. */
  99753. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  99754. /**
  99755. * Default skybox texture URL.
  99756. */
  99757. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  99758. /**
  99759. * Default environment texture URL.
  99760. */
  99761. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  99762. return EnvironmentHelper;
  99763. }());
  99764. BABYLON.EnvironmentHelper = EnvironmentHelper;
  99765. })(BABYLON || (BABYLON = {}));
  99766. //# sourceMappingURL=babylon.environmentHelper.js.map
  99767. var BABYLON;
  99768. (function (BABYLON) {
  99769. /**
  99770. * This class is made for on one-liner static method to help creating particle systems.
  99771. */
  99772. var ParticleHelper = /** @class */ (function () {
  99773. function ParticleHelper() {
  99774. }
  99775. /**
  99776. * This is the main static method (one-liner) of this helper to create different particle systems.
  99777. * @param type This string represents the type to the particle system to create
  99778. * @param emitter The object where the particle system will start to emit from.
  99779. * @param scene The scene where the particle system should live.
  99780. * @param gpu If the system will use gpu.
  99781. * @returns the ParticleSystem created.
  99782. */
  99783. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  99784. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  99785. if (gpu === void 0) { gpu = false; }
  99786. return new Promise(function (resolve, reject) {
  99787. if (!scene) {
  99788. scene = BABYLON.Engine.LastCreatedScene;
  99789. ;
  99790. }
  99791. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  99792. return reject("Particle system with GPU is not supported.");
  99793. }
  99794. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  99795. var newData = JSON.parse(data.toString());
  99796. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  99797. }, undefined, undefined, undefined, function (req, exception) {
  99798. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  99799. });
  99800. });
  99801. };
  99802. /**
  99803. * Static function used to create a new particle system from a IParticleSystemData
  99804. * @param data defines the source data
  99805. * @param scene defines the hosting scene
  99806. * @param emitter defines the particle emitter
  99807. * @returns a new ParticleSystem based on referenced data
  99808. */
  99809. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  99810. // Create a particle system
  99811. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  99812. // Where the particles come from
  99813. system.emitter = emitter; // the starting object, the emitter
  99814. ParticleHelper.UpdateSystem(system, data, scene);
  99815. return system;
  99816. };
  99817. /**
  99818. * Static function used to update a particle system from a IParticleSystemData
  99819. * @param system defines the particle system to update
  99820. * @param data defines the source data
  99821. * @param scene defines the hosting scene
  99822. */
  99823. ParticleHelper.UpdateSystem = function (system, data, scene) {
  99824. // Texture of each particle
  99825. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  99826. // Colors of all particles
  99827. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  99828. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  99829. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  99830. // Size of each particle (random between...
  99831. system.minSize = data.minSize;
  99832. system.maxSize = data.maxSize;
  99833. // Life time of each particle (random between...
  99834. system.minLifeTime = data.minLifeTime;
  99835. system.maxLifeTime = data.maxLifeTime;
  99836. // Emission rate
  99837. system.emitRate = data.emitRate;
  99838. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  99839. system.blendMode = data.blendMode;
  99840. // Set the gravity of all particles
  99841. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  99842. // Angular speed, in radians
  99843. system.minAngularSpeed = data.minAngularSpeed;
  99844. system.maxAngularSpeed = data.maxAngularSpeed;
  99845. // Speed
  99846. system.minEmitPower = data.minEmitPower;
  99847. system.maxEmitPower = data.maxEmitPower;
  99848. system.updateSpeed = data.updateSpeed;
  99849. switch (data.emitterType) {
  99850. case "box":
  99851. if (!data.direction1 || !data.direction2) {
  99852. throw new Error("Directions are missing in this particle system.");
  99853. }
  99854. if (!data.minEmitBox || !data.maxEmitBox) {
  99855. throw new Error("EmitBox is missing in this particle system.");
  99856. }
  99857. 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));
  99858. break;
  99859. case "sphere":
  99860. system.createSphereEmitter(data.radius);
  99861. break;
  99862. case "directed_sphere":
  99863. if (!data.direction1 || !data.direction2) {
  99864. throw new Error("Directions are missing in this particle system.");
  99865. }
  99866. 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));
  99867. break;
  99868. case "cone":
  99869. system.createConeEmitter(data.radius, data.angle);
  99870. break;
  99871. default:
  99872. break;
  99873. }
  99874. };
  99875. /**
  99876. * Base Assets URL.
  99877. */
  99878. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  99879. return ParticleHelper;
  99880. }());
  99881. BABYLON.ParticleHelper = ParticleHelper;
  99882. })(BABYLON || (BABYLON = {}));
  99883. //# sourceMappingURL=babylon.particleHelper.js.map
  99884. var BABYLON;
  99885. (function (BABYLON) {
  99886. /**
  99887. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  99888. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  99889. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  99890. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  99891. */
  99892. var VideoDome = /** @class */ (function (_super) {
  99893. __extends(VideoDome, _super);
  99894. /**
  99895. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  99896. * @param name Element's name, child elements will append suffixes for their own names.
  99897. * @param urlsOrVideo defines the url(s) or the video element to use
  99898. * @param options An object containing optional or exposed sub element properties
  99899. */
  99900. function VideoDome(name, urlsOrVideo, options, scene) {
  99901. var _this = _super.call(this, name, scene) || this;
  99902. // set defaults and manage values
  99903. name = name || "videoDome";
  99904. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  99905. options.clickToPlay = Boolean(options.clickToPlay);
  99906. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  99907. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  99908. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  99909. // create
  99910. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  99911. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  99912. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  99913. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  99914. flat: false,
  99915. radius: options.size,
  99916. subdivisions: options.resolution,
  99917. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  99918. }, scene);
  99919. // configure material
  99920. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  99921. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  99922. material.reflectionTexture = _this._videoTexture;
  99923. material.useEquirectangularFOV = true;
  99924. material.fovMultiplier = 1.0;
  99925. // configure mesh
  99926. _this._mesh.material = material;
  99927. _this._mesh.parent = _this;
  99928. // optional configuration
  99929. if (options.clickToPlay) {
  99930. scene.onPointerUp = function () {
  99931. _this._videoTexture.video.play();
  99932. };
  99933. }
  99934. return _this;
  99935. }
  99936. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  99937. /**
  99938. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  99939. * Also see the options.resolution property.
  99940. */
  99941. get: function () {
  99942. return this._material.fovMultiplier;
  99943. },
  99944. set: function (value) {
  99945. this._material.fovMultiplier = value;
  99946. },
  99947. enumerable: true,
  99948. configurable: true
  99949. });
  99950. /**
  99951. * Releases resources associated with this node.
  99952. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  99953. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  99954. */
  99955. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  99956. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  99957. this._videoTexture.dispose();
  99958. this._mesh.dispose();
  99959. this._material.dispose();
  99960. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  99961. };
  99962. return VideoDome;
  99963. }(BABYLON.Node));
  99964. BABYLON.VideoDome = VideoDome;
  99965. })(BABYLON || (BABYLON = {}));
  99966. //# sourceMappingURL=babylon.videoDome.js.map
  99967. var BABYLON;
  99968. (function (BABYLON) {
  99969. /**
  99970. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  99971. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  99972. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  99973. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  99974. */
  99975. var PhotoDome = /** @class */ (function (_super) {
  99976. __extends(PhotoDome, _super);
  99977. /**
  99978. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  99979. * @param name Element's name, child elements will append suffixes for their own names.
  99980. * @param urlsOfPhoto define the url of the photo to display
  99981. * @param options An object containing optional or exposed sub element properties
  99982. */
  99983. function PhotoDome(name, urlOfPhoto, options, scene) {
  99984. var _this = _super.call(this, name, scene) || this;
  99985. // set defaults and manage values
  99986. name = name || "photoDome";
  99987. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  99988. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  99989. // create
  99990. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  99991. var texture = _this._photoTexture = new BABYLON.Texture(urlOfPhoto, scene);
  99992. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  99993. flat: false,
  99994. radius: options.size,
  99995. subdivisions: options.resolution,
  99996. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  99997. }, scene);
  99998. // configure material
  99999. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  100000. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  100001. material.reflectionTexture = _this._photoTexture;
  100002. material.useEquirectangularFOV = true;
  100003. material.fovMultiplier = 1.0;
  100004. // configure mesh
  100005. _this._mesh.material = material;
  100006. _this._mesh.parent = _this;
  100007. return _this;
  100008. }
  100009. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  100010. /**
  100011. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100012. * Also see the options.resolution property.
  100013. */
  100014. get: function () {
  100015. return this._material.fovMultiplier;
  100016. },
  100017. set: function (value) {
  100018. this._material.fovMultiplier = value;
  100019. },
  100020. enumerable: true,
  100021. configurable: true
  100022. });
  100023. /**
  100024. * Releases resources associated with this node.
  100025. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  100026. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  100027. */
  100028. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  100029. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  100030. this._photoTexture.dispose();
  100031. this._mesh.dispose();
  100032. this._material.dispose();
  100033. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  100034. };
  100035. return PhotoDome;
  100036. }(BABYLON.Node));
  100037. BABYLON.PhotoDome = PhotoDome;
  100038. })(BABYLON || (BABYLON = {}));
  100039. //# sourceMappingURL=babylon.photoDome.js.map
  100040. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute 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\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  100041. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};